如何从此事件函数访问对象的父属性?

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

我动态创建了Sound对象

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
}

我试过了

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

但是它抛出错误。 所以我需要从 onSoundLoaded() 函数中获取 files["file1"]["id"] 。可能吗?

严格回答你的问题,你的"snd"对象和你的"file1"对象之间没有层级关系。 parent 关键字用于显示对象层次结构。

您必须遍历文件对象才能找到您的匹配项:

//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
    }
}

稍微超出您的问题范围,使用包含与该声音相关的所有所需属性的自定义 class/model 确实会更清晰、更容易。例如:(您的 swf/fla 旁边的一个名为 MySound.as 的文件包含以下内容:

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);
        }
    }
}

现在,您可以这样做:

//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);
}

根据您正在做的事情,您可以在 MySound 中收听和响应完整事件(已加载)class,进一步将其抽象出来。