AS3事件分发的原理和实现


1. 首先定义一个自定义事件类MyEvent.as,该事件继承了Event

 

 1 package
2 {
3 import flash.events.Event;
4
5 public class MyEvent extends Event
6 {
7 public static const SUCCESS:String = "success";
8 public static const FAIL:String = "fail";
9
10 //直接用super调用Event的方法
11 public function MyEvent(type:String, bubbles:Boolean=false, cancelable:Boolean=false)
12 {
13 super(type, bubbles, cancelable);
14 }
15 }
16 }

 

2.定义能实现事件分发功能的类Service.as,该类继承了EventDispatcher类,从而使得该类具有了事件分发的功能,其中hello函数只是为了区分成功和失败两种事件而进行的模拟。

 

 1 package
2 {
3 import flash.events.EventDispatcher;
4
5 public class Service extends EventDispatcher
6 {
7 public function Service()
8 {
9
10 }
11 //只是模拟了一下,实际应该不是这样用的,帮助理解吧。
12 public function hello(tag:String):void{
13 var event:MyEvent;
14 if(tag == "world"){
15 event = new MyEvent(MyEvent.SUCCESS);
16 }else{
17 event = new MyEvent(MyEvent.FAIL);
18 }
19 dispatchEvent(event);
20 }
21
22 }
23 }


3.使用测试类DispatchEventTest.as,要使用Service提供的hello函数,必须知道Service能派发出成功和失败两种事件,因此测试类DispatchEventTest会监听两个,当测试类调用hello("world")时,Service类就会派发成功事件,从而跳转到DispatchEventTest类的相应监听函数中。

 

package
{
import flash.display.Sprite;
import flash.events.Event;
import flash.events.EventDispatcher;

public class DispatchEventTest extends Sprite
{

public function DispatchEventTest()
{
var service:Service = new Service();
//监听事件派发
service.addEventListener(MyEvent.SUCCESS,onSuccess);
service.addEventListener(MyEvent.FAIL,onFail);
service.hello("world");
}
private function onSuccess(e:MyEvent):void{
trace("success");
}

private function onFail(e:MyEvent):void{
trace("fail");
}
}
}

 

输出结果:

success

实例程序:https://files.cnblogs.com/carlosfu/DispatchEventTest.rar

 

相關文章:
使用 dispatchEvent() 方法
http://www.cnblogs.com/baobaoandxiangxiang/archive/2006/10/06/522238.html
让dispatchEvent更高效
http://www.flashas.net/html/flashas/ASxiaojiqiao/20081211/3797.html
ActionScript 3 天地會
http://bbs.actionscript3.cn/thread-10315-1-1.html
dispatchEvent的应用
http://shirley.gx.blog.163.com/blog/static/608657612008929104053313/




 

posted @ 2012-03-02 15:08  carlosfu  阅读(475)  评论(0编辑  收藏  举报