as3 - 从父swf到子swf的dispatchEvent

sol*_*sol 4 flash events dispatcher actionscript-3

我有一个主要的"父"swf加载其他几个swfs.如果在主SWF中发生了某些事情,我需要告诉其中一个孩子swf.

这似乎相反,相反.任何一个孩子都可以简单地调用Event(),我可以设置主swf来监听事件.但是,我无法让子swf捕获父级调度的任何事件.怎么做?

Oli*_*ner 5

好的,所以如果你已经知道了大部分内容,我很抱歉......但这似乎是一个非常普遍的问题,并不是很明显.

在AS3的对象在显示列表调度的事件可以听了,因为他们泡,而无需指定发起对象的显示列表层次结构.(当然假设事件的冒泡属性设置为true).因此,文档类(_root的旧概念)可以响应任何显示对象的鼠标点击,无论嵌套有多深,

addEventListener(MouseEvent.CLICK, _onMouseClick)

在任何其他情况下 - 例如冒泡设置为false,广播器不是显示列表上的InteractiveObject,或者(如在您的情况下)侦听器低于显示列表层次结构中的广播器 - 广播事件的对象必须是特别听取:

fooInstance.addEventListener(Event.BAR, _bazFunc)
而不是公正的
addEventListener(Event.BAR, _bazFunc)

基本上,您需要将对父对象的引用传递给子swf,以便它可以将事件处理程序附加到它.

一种方法是通过显示列表将子事件从子类调度到父类(一旦子项加载并完全初始化).父级使用此事件的event.target属性来引用子级并在其上设置parentClass变量.然后可以使用它来附加侦听器:

package {


    class ChildClass 
    {
        private var __parentClass:ParentClass;

        // EventID to listen for in ParentClass
        public static const INITIALISED:String = "childInitialised";

        // Constructor
        function ChildClass() 
        {
            // Do initialising stuff, then call:
            _onInitialised();
        }

        private function _onInitialised():void
        {
            // Dispatch event via display hierarchy
            // ParentClass instance listens for generic events of this type
            // e.g. in ParentClass:
            //     addEventListener(ChildClass.INITIALISED, _onChildInitialised);
            //     function _onChildInitialised(event:Event):void {
            //         event.target.parentClass = this;
            //     }
            // @see mutator method "set parentClass" below
            dispatchEvent(new Event(ChildClass.INITIALISED, true);
        }

        public function set parentClass(value:ParentClass):void
        {
            __parentClass = value;

            // Listen for the events you need to respond to
            __parentClass.addEventListener(ParentClass.FOO, _onParentFoo, false, 0, true);
            __parentClass.addEventListener(ParentClass.BAR, _onParentBar, false, 0, true);
        }

        private function _onParentFoo(event:Event):void
        {
            ...
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

调度自定义ChildSWFEvent - 即不使用上面定义的类定义 - 将使这更加灵活,因为ParentClass实例可以监听任何子swf广播的常见ChildSWFEvent.INITIALISED事件,其中上下文作为附加信息传递参数.