2012年4月18日 星期三

自訂事件偵聽DEMO


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

/**
* 自訂一個預叫計程車流程,
* Customer:客人,
* CallTaxiEvent:呼叫計程車事件,
* Driver.reply:司機的回覆
* ...
* @author Ray Cheng
*/
public class Main extends Sprite
{

public function Main():void
{
if (stage) init();
else addEventListener(Event.ADDED_TO_STAGE, init);
}

private function init(e:Event = null):void
{
removeEventListener(Event.ADDED_TO_STAGE, init);
create()
}

private function create():void
{
var _customer:Customer = new Customer("RAY");

var _driver:Driver = new Driver();

_customer.addEventListener(CallTaxiEvent.START_CALL, _driver.reply);//--開始偵聽

_customer.calltaxi();//--客人發出事件請求

}
}
}

//------------CallTaxiEvent


public class CallTaxiEvent extends Event
{
public static const START_CALL:String = "開始撥打計程車專線";
private var _array:Array;//--叫車內容

public function CallTaxiEvent()
{
super(START_CALL) //將靜態屬性START_CALL
}

public function get array():Array
{
return _array;
}

public function set array(value:Array):void
{
_array = value;
}
}

//------------Driver


public class Driver
{

public function Driver()
{
//---也可以寫在建構涵式
}

public function reply(e:CallTaxiEvent):void {

trace("OK...客人您的叫車時間是---"+e.array)
                        注意是e.array   不是e.target.array
}

}

//------------Customer


public class Customer extends EventDispatcher
{
private var _name:String = "";

public function Customer(pName:String)
{
_name = pName;
}

//----執行叫車動作
public function calltaxi():void {

var $callEvent:CallTaxiEvent = new CallTaxiEvent();
$callEvent.array = ["17:20", "忠孝東路-仁愛路"];

dispatchEvent($callEvent);
}

}



沒有留言:

張貼留言

我的留言版