您可以设置几个简单的类来管理事件侦听器的集合。让我们调用 collection EventBatch
,它可能如下所示:
public class EventBatch
{
private var _items:Vector.<EventBatchItem> = new <EventBatchItem>[];
public function addListener(target:IEventDispatcher, type:String, callback:Function):void
{
var item:EventBatchItem = new EventBatchItem(target, type, callback);
_items.push(item);
target.addEventListener(type, callback);
}
public function removeAll():void
{
for each(var i:EventBatchItem in _items)
{
i.target.removeEventListener(i.type, i.callback);
i.dispose();
}
_items = new <EventBatchItem>[];
}
}
这是代表项目的随附模型:
internal class EventBatchItem
{
private var _target:IEventDispatcher;
private var _type:String;
private var _callback:Function;
public function EventBatchItem(target:IEventDispatcher, type:String, callback:Function)
{
_target = target;
_type = type;
_callback = callback;
}
internal function dispose():void
{
_target = null;
_callback = null;
}
internal function get target():IEventDispatcher{ return _target; }
internal function get type():String{ return _type; }
internal function get callback():Function{ return _callback; }
}
这样,您可以像这样添加事件侦听器:
var batch:EventBatch = new EventBatch();
batch.addListener(urlLoader, Event.COMPLETE, completeHandler);
batch.addListener(urlLoader, SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler);
batch.addListener(urlLoader, IOErrorEvent.IO_ERROR, ioErrorHandler);
在任何这些侦听器函数中,只需使用以下.removeAll()
方法:
batch.removeAll();