Search code examples
actionscript-3flashobjectparent

How to access object's parent's propertie, from his event function?


I have dynamically created Sound object

var     files:Object={};
files["file1"]={};
files["file1"]["snd"]=new Sound();
...... //url etc
files["file1"]["id"]='01'; //that's important
files["file1"]["snd"].addEventListener(Event.COMPLETE, onSoundLoaded);

function onSoundLoaded(event:Event):void 
//// somehow I need to get the `id` property of its parent
}

I tried

var localRef:Object = event.target as Object;
var localRef:Object = event.target.parent as Object;

But it throws error. So I need to get the files["file1"]["id"] from the onSoundLoaded() function. Is it possible?


Solution

  • Strictly answering your question, there is no hierarchical relationship between your "snd" object and your "file1" object. The parent keyword is for display object hierarchy.

    You'll have to iterate over the files object to find your match:

    //in the sound loaded function
    for(var f:Object in files){
        if(f["snd"] === event.currentTarget){
            var myId:String = f["id"];
            //do something with the id
    
            break; //don't keep looping
        }
    }
    

    To go beyond the scope of your question a bit, it would indeed be much cleaner and easier to use a custom class/model that encompasses all the properties you need that relate to that one sound. Something like this for example: (a file next to your swf/fla called MySound.as containing the following:

    package {
        import flash.media.Sound;
        import flash.media.SoundLoaderContext;
        import flash.net.URLRequest;
    
        public class MySound extends Sound {
            public var id:String;
    
            public function MySound(id_:String, stream:URLRequest, context:SoundLoaderContext):void {
                id = id_;
                //call the original constructor method for Sound
                super(stream, context);
            }
        }
    }
    

    Now, you can do this:

    //use a vector/array instead of an object
    var sounds:Vector.<MySound> = new Vector.<MySound>();
    
    var sound:MySound = new MySound("01");
    sound.addEventListener(Event.COMPLETE, onSoundLoaded);
    
    //add to sound array
    sounds.push(sound);
    
    function onSoundLoaded(e:Event):void {
        var sound:MySound = MySound(e.currentTarget);
    
        trace("My ID: ", sound.id);
    }
    

    Depending on what you're doing, you could listen and respond to the complete event (loaded) inside your MySound class further abstracting it out.