網頁

2011年4月30日 星期六

ActionScript - addEventListener, dispatchEvent

Last Update: 2011/05/01 13:28+08


Intro


關於 ActionScript 的 addEventListener / dispatchEvent
這2個 method 被定義在 EventDispatcher
因此咱們的物件只要有繼承到這個, 都可以使用

講到 dispatchEvent 通常就應該是自定義event了
不然用 addEventListener 就夠了唄


Listener / Dispatch



這是自訂的類別

public class MyTest extends EventDispatcher
{
public static const Event_UnknownComplete:String="MyTest.Event_UnknownComplete";
public function doEvent_UnknownComplete():void{
this.dispatchEvent(new Event(Event_UnknownComplete));
}
public function start():void{
setTimeout(doEvent_UnknownComplete,2000);
}
}



在Application的測試Code

protected function application1_creationCompleteHandler(event:FlexEvent):void
{
var test : MyTest = new MyTest();
test.addEventListener(MyTest.Event_UnknownComplete, test_Event_UnknownComplete, false);
test.addEventListener(MyTest.Event_UnknownComplete, function(event:Event):void{
Alert.show("Event_UnknownComplete be dispatched 2");
});
test.start();
}

protected function test_Event_UnknownComplete(event:Event):void{
Alert.show("Event_UnknownComplete be dispatched 1");
}