观察者模式
1.继承AsEventDispatcher类可以发送事件,添加事件侦听
package
{
import flash.events.Event;
import flash.utils.Dictionary;
public class AsEventDispatcher
{
//[事件类型]=事件处理函数
private var receive:Dictionary = new Dictionary();
public function AsEventDispatcher()
{
}
//添加接收者
public function addEventListener(type:String, listener:Function):void
{
receive[type] = listener;
}
//清除接收者
public function removeEventListener(type:String, listener:Function):void
{
trace("removeEventListener");
for(var _type:String in receive)
{
if(_type == type &&receive[_type] == listener)
{
delete receive[_type];
}
}
}
//发送事件
public function dispatchEvent(evt:AsEvent):void
{
for(var _type:String in receive)
{
if(_type == evt.type)
{
receive[evt.type](evt);
}
}
}
}
}
2. 通过dispatchEvent发出的事件都要是AsEvent,或者AsEvent的子类
package
{
public class AsEvent
{
private var _type:String;
public function AsEvent(_typeStr:String)
{
_type = _typeStr;
}
public function get type():String
{
return _type;
}
}
}
3.运行
package
{
public class cs extends AsEventDispatcher
{
public function cs()
{
this.addEventListener("Event", onEvent);
//this.removeEventListener("Event", onEvent);
this.dispatchEvent(new AsEvent("Event"));
}
private function onEvent(evt:AsEvent):void
{
trace("..."); //输出...
}
}
}

浙公网安备 33010602011771号