共享一个消费分发器
package com.events
{import flash.utils.Dictionary;
/**
* 消息分发器
* @author azu
*
*/
public class MsgDispatcher
{
public var map:Dictionary;
private static var instance:MsgDispatcher;
public function MsgDispatcher()
{
map = new Dictionary();
}
private static function getInstance():MsgDispatcher
{
return instance ||= new MsgDispatcher();
}
private function addEvent(type:String, fun:Function):void
{
var funcs:Array=map[type];
if (funcs == null)
{
funcs=[];
map[type] = funcs;
}
else
{
if (funcs.indexOf(fun) != -1)
{
return;
}
}
funcs.push(fun);
}
private function removeEvent(type:String, fun:Function):void
{
var funcs:Array=map[type];
if (funcs)
{
var index:int=funcs.indexOf(fun);
if (index != -1)
{
funcs.splice(index, 1);
}
}
}
private function execute(type:String, param:Object):void
{
var funcs:Array=map[type];
if (funcs == null)
{
return;
}
for each(var fun:Function in funcs)
{
if (param == null)
{
if(fun!=null)
{
fun.apply(null,null);
}
}
else
{
if(fun!=null)
{
fun.apply(null,[param]);
}
}
}
}
/**
* 分发事件
* @param type
* @param param
*
*/
public static function sendMessge(type:String, param:Object=null):void
{
getInstance().execute(type, param);
}
/**
* 注册事件类型 和监听方法
* @param type 事件类型
* @param fun
*
*/
public static function register(type:String, fun:Function):void
{
getInstance().addEvent(type, fun);
}
/**
* 删除事件和对应的监听方法
* @param type 事件类型
* @param fun
*
*/
public static function remove(type:String, fun:Function):void
{
getInstance().removeEvent(type, fun);
}
}
}
------------------------------------------------------------------------------------------------------------------------
使用方法
MsgDispatcher.sendMessge(MsgCommand.XXX_SELECT_MAP_POINT,this.good)
这里发出消息
-------------------------------------------------------------------------------------------------
override protected function addedToStageHandler(event:Event):void
{
MsgDispatcher.register(XXX_SELECT_MAP_POINT, onClickImg);
}
然后注册监听就可有回调用了
---------------------------------------------------------------------------------------
在写一个事件类
package com.events
{
public class MsgCommand
{
public function MsgCommand()
{
}
/**
*xxx
*/
public static const XXX_SELECT_MAP_POINT:String ="XXX_SELECT_MAP_POINT";
}
}
----------------------------------
这种做法就是可以减少new的事件 少一些内存占用