Barefoot Development

Add properties to already existing Classes in Flash

This is a simple way to store a property in the Sound Class of Flash for use in the onSoundComplete method (or any built-in method with any built-in class). The theory is called casting:


var my_sound: Object = new Sound();
my_sound.id = this.id;
my_sound.attachSound("someSound");
my_sound.start();
my_sound.onSoundComplete = function()
{
// stop the animation
_root["person" + id].stop();
}


Notice the declaration of Object, in the first line. Should my_sound be defined as Sound, the second line would fail because id is not a predefined property of the Sound class. By declaring my_sound as a generic Object, adding properties is allowed. All Sound properties and methods are still available even with the generic Object definition, hence the use of the onSoundComplete method on line 5. Notice the use of the id property to dynamically define an object on the _root.

More can be read about casting in Flash in Colin Moock's latest book from O'Reilly called "Essential Actionscript 2.0."

Michael Krisher, Senior Developer at Barefoot.

1 comments

  1. Blogger Dr. B. said:  

    This is such a simple but helpful technique -- I just used it today. I was doing an animation with Fuse in a component's class definition. I needed to get a reference to the component within the onComplete event. Typically, the reference to the calling component instance would not be available. However, I was able to add a reference to "this" as a property of the Fuse object, then access that from event.target as shown:

    -----
    var fuse:Object = new Fuse(fActions);
    fuse.thePiece = this;

    var listener:Object = new Object();
    listener.onComplete = function(event:Object) {
    event.target.thePiece.clearFuse();
    };
    fuse.addEventListener("onComplete", listener);

    fuse.start();
    -----

Post a Comment

« Home