/**

EventDelegate acts as a proxy event handler, so that events can be handled in a different scope than the listener or using a different name than the event name.

@class EventDelegate @author Peter Hall @date 20/05/2004 */ class com.peterjoel.events.EventDelegate { // the reference to the event handler function private var funcRef:Function; // the scope, in which to execute the handler function private var target:Object; // if true, event will be removed next time it is dispatched private var killFlag:Boolean = false; /**

Constructor for EventDelegate.

*/ public function EventDelegate(targ:Object, func:Function){ target = targ; funcRef = func; } /**

Factory method; creates an instance of EventDelegate. Included for consistency with mx.utils.Delegate, but you can still create an instance with new EventDelegate();

*/ public static function create(obj:Object, func:Function):EventDelegate{ return new EventDelegate(obj, func); } /**

Factory method; creates a copy of the delegate, applying to a different target.

*/ public function createDelegate(obj:Object):EventDelegate{ return new EventDelegate(obj, funcRef); } private function handleEvent(evt:Object):Object{ if(killFlag){ // delegate.kill() was called before the first time this event was handled // so don't handle the event and stop listening for it any more stopListeningToEvent(evt); return null; }else{ return funcRef.call(target, evt, this); } } /**

Stops the Delegate from listening to the events any more. Invoke this method before deleting the delegate instance to ensure that the event does not continue to be listened for.

This method has a permanent effect. To temporarily stop listening for an event, use stopListeningToEvent().

*/ public function kill():Void{ // the listener removal is implemented lazily, as we may not know the name of the // event at this point, in order to remove this as a listener. // Also, it means we don't have to store references to the event source as well as // the listener, which would be risky, as objects could end up hanging around // when we think they are deleted killFlag = true; delete target; delete funcRef; } /**

Stops listening to a specific event, from a given source. This is a shortcut method to dispatcher.removeEventListener(), for when you have an example event object from the event source and type that you want to stop listening to.

@param eventObj An event object from the source, to stop listening to. */ public function stopListeningToEvent(eventObj:Object){ eventObj.target.removeEventListener(eventObj.type, this); } }