星期五, 1月 22, 2010

flash 自定義事件

dispatchEvent 擲出事件體
need:
import flash.events.EventDispatcher;

Event 事件體
need:
import flash.events.Event;



較完整用法(官網):

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

public class EventDispatcherExample extends Sprite {

public function EventDispatcherExample() {
var dispatcher:CustomDispatcher = new CustomDispatcher();
dispatcher.addEventListener(CustomDispatcher.ACTION, actionHandler);
dispatcher.doAction();
}

private function actionHandler(event:Event):void {
trace("actionHandler: " + event);
}
}
}

import flash.events.EventDispatcher;
import flash.events.Event;

class CustomDispatcher extends EventDispatcher {
public static var ACTION:String = "action";

public function doAction():void {
dispatchEvent(new Event(CustomDispatcher.ACTION));
}
}
ActionScript 3.0 語言和組件參考 - EventDispatcher



另一種用法:

//首先我們要導入EventDispatcher
import mx.events.EventDispatcher;

class testEvent extends MovieClip{
function testEvent(){
//在構造函數中初始化
EventDispatcher.initialize(this);
}

//定義這三個方法

function dispatchEvent(){}
function addEventListener(){}
function removeEventListener(){}

function sendOK(){
//定義事件onSend
var eventObj1:Object = {target:this,type:"onSend"};
dispatchEvent(eventObj1);
trace("OK");
//定義事件onComplete
var eventObj2:Object = {target:this,type:"onComplete"}; dispatchEvent(eventObj2); }
}

怎麼用我們的事件呢?往下看!
新建一個FLA,輸入以下代碼:
大家還記得UI組建的事件處理函數麼,對這個和UI組建的差不多,都是addEventListener和removoeEventListener。

var testObj:testEvent = new testEvent();
var eventObj1:Object = new Object();
eventObj1.onSend = function(obj){ trace("type:"+obj.type); }

var eventObj2:Object = new Object();
eventObj2.onComplete = function(obj){ trace("type:"+obj.type); }
testObj.addEventListener("onSend",eventObj1);
testObj.addEventListener("onComplete",eventObj2);
testObj.sendOK();

用EventDispatcher自定義事件



其他用法(自認為較簡便):

/* 擲出事件體 */
dispatchEvent(new Event("onCompletePressCover"));

解釋:
建立新事件體 "onCompletePressCover" 並用 dispatchEvent 擲出

/* 監聽事件體 */
this.addEventListener("onCompletePressCover", removeRenderListener);

沒有留言:

張貼留言