as2时代直接在dispatchEvent的时候跟上想跟的参数就可以了,as3增加了一个Event的继承类来承担其中的信息传递,不过看书看到关键时刻居然就没有了。于是笔记一下类实例怎么向外发送事件和传递参数,来点实用的。
发送事件的Guest,在Guest内发送”do_b”的Event:
- var e:GuestEvent = new GuestEvent(GuestEvent.DO_B);
- e.args = {author:"hirokimo",time:"21:10"};
- this.dispatchEvent(e);
这时候为了传递参数,使用一个继承Event的自定义事件类GuestEvent:
- package
- {
- import flash.events.Event;
- public class GuestEvent extends Event
- {
- public static const DO_A:String = "do_a";
- public static const DO_B:String = "do_b";
- public static const DO_C:String = "do_c";
- public var args:*;
- public function GuestEvent(_type:String)
- {
- super(_type);
- }
- }
- }
最后,在类外面添加侦听和接收的地方:
- package
- {
- public class EventTest
- {
- public function EventTest()
- {
- var guest:Guest = new Guest();
- guest.addEventListener(GuestEvent.DO_B,handleB);
- }
- private function handleB(e:GuestEvent):void
- {
- trace("author:"+e.args.author
- +" time:"+e.args.time);
- //author:hirokimo time:21:10
- }
- }
- }
大功告成,之后就可以顺利的发送事件参数了。
不过有一点值得注意:Guest类里有时需要在初始化后直接dispatch一个Event出来,这时候因为外部addEventListener动作还没有完成,listener是收不到事件的。
这个问题很容易被忽略,如果一定要这么做,可以:
1.Guest初始化后timer几百毫秒再dispatch 或者
2.外面addEventListener完之后,主动调guest.xxx来发送。