是否可以听取另一个类触发的事件?

时间:2011-10-15 22:50:40

标签: actionscript-3 actionscript event-listener event-dispatching

我有3节课:

识别URL更改的类(使用Asual的SWFAddress):

package swfaddress {

import flash.display.MovieClip;
import com.asual.swfaddress.*;

 public class SwfAddress extends MovieClip {

 private var dispatcher:Dispatch = new Dispatch;

 public function SwfAddress():void {
  SWFAddress.addEventListener(SWFAddressEvent.CHANGE, onChange);
 }

 private function onChange(e:SWFAddressEvent):void {
  dispatcher.changed();
 }
}
}

“Dispatch”类,用于验证URL并在完成时调度事件

package swfaddress {
 import flash.events.Event;
 import flash.events.EventDispatcher;

 public class Dispatch extends EventDispatcher {

  public static const CHANGED:String  = "changed";

  public function changed ():void {

    // some operations validating the URL

   dispatchEvent(new Event(Dispatch.CHANGED));
  }
 }
}

其他包中应该在验证过程完成后收到信息的其他类。

package menu {
import swfaddress.*

public class MenuPanel extends MovieClip {
var swfRead:Dispatch = new Dispatch;

public function MenuPanel():void {
 swfRead.addEventListener(Dispatch.CHANGED, onChange);
}

private function onChange(e:Event):void {
 trace("Hello World");
}
}

并且“Hello World”从未出现在输出窗口中 - 所以我不确定我的MenuPanel是否有可能收到有关完成其他类别触发的验证的信息?

1 个答案:

答案 0 :(得分:1)

您正在创建调度程序的两个不同实例,因此调用URL以验证URL的实例与您在MenuPanel类中侦听的实例不同。

解决这个问题的一个简单方法是将Dispatch类设为单例,这样只存在一个实例,并且可以从应用程序的不同点引用它。这通过为Dispatch类提供一个静态方法来工作,该方法返回自身的自包含实例。然后,只要您想要引用该类而不是使用Dispatch.getInstance()关键字,就可以调用new

急件:

package swfaddress
{
    import flash.events.Event;
    import flash.events.EventDispatcher;


    public class Dispatch extends EventDispatcher
    {
        // singleton instance
        private static var _instance:Dispatch;
        private static var _allowInstance:Boolean;

        public static const CHANGED:String  = "changed";

        // get singleton instance of Dispatch
        public static function getInstance():Dispatch 
        {
            if (Dispatch._instance == null) {
                Dispatch._allowInstance = true;
                Dispatch._instance = new Dispatch();
                Dispatch._allowInstance = false;
            }
            return Dispatch._instance;
        }

        public function Dispatch() 
        {
            if (!Dispatch._allowInstance)
            {
                throw new Error("Error: Use Dispatch.getInstance() instead of the new keyword.");
            }
        }

        public function changed():void {
            //some operations validating the URL
            dispatchEvent(new Event(Dispatch.CHANGED));
        }
    }
}

获取参考:

private var dispatcher:Dispatch = Dispatch.getInstance();