关于as3事件的笔记

as2时代直接在dispatchEvent的时候跟上想跟的参数就可以了,as3增加了一个Event的继承类来承担其中的信息传递,不过看书看到关键时刻居然就没有了。于是笔记一下类实例怎么向外发送事件和传递参数,来点实用的。
发送事件的Guest,在Guest内发送”do_b”的Event:

  1. var e:GuestEvent = new GuestEvent(GuestEvent.DO_B);
  2. e.args = {author:"hirokimo",time:"21:10"};
  3. this.dispatchEvent(e);

这时候为了传递参数,使用一个继承Event的自定义事件类GuestEvent:

  1. package
  2. {
  3.     import flash.events.Event;   
  4.     public class GuestEvent extends Event
  5.     {
  6.         public static const DO_A:String = "do_a";
  7.         public static const DO_B:String = "do_b";
  8.         public static const DO_C:String = "do_c";      
  9.         public var args:*;   
  10.         public function GuestEvent(_type:String)
  11.         {
  12.             super(_type);
  13.         }
  14.     }
  15. }

最后,在类外面添加侦听和接收的地方:

  1. package
  2. {
  3.     public class EventTest
  4.     {
  5.         public function EventTest()
  6.         {
  7.             var guest:Guest = new Guest();
  8.             guest.addEventListener(GuestEvent.DO_B,handleB);
  9.         }
  10.         private function handleB(e:GuestEvent):void
  11.         {
  12.             trace("author:"+e.args.author
  13.             +" time:"+e.args.time);
  14.             //author:hirokimo time:21:10
  15.         }
  16.     }
  17. }

大功告成,之后就可以顺利的发送事件参数了。
不过有一点值得注意:Guest类里有时需要在初始化后直接dispatch一个Event出来,这时候因为外部addEventListener动作还没有完成,listener是收不到事件的。
这个问题很容易被忽略,如果一定要这么做,可以:
1.Guest初始化后timer几百毫秒再dispatch 或者
2.外面addEventListener完之后,主动调guest.xxx来发送。

Leave a Reply