[flash] Only Once EventListener
package; import flash.events.Event; import flash.events.EventDispatcher; import flash.events.IEventDispatcher; class EventDispatcherTools { public static function addOnceListener (dispatcher:IEventDispatcher, type : String, listener : Event->Void) { var f:Event->Void = null; f = function (e:Event) { cast (e.target, IEventDispatcher).removeEventListener(e.type, f); listener(e); } dispatcher.addEventListener(type, f); } } // usage using Main.EventDispatcherTools; class Main { public static function main ():Void { var e : EventDispatcher = new EventDispatcher(); // add a listener which is called only once e.addOnceListener(Event.COMPLETE, function (_) trace("complete, listener will be removed after first call.")); trace(e.hasEventListener(Event.COMPLETE)); // yes there is a listener e.dispatchEvent(new Event(Event.COMPLETE)); // first dispatch trace(e.hasEventListener(Event.COMPLETE)); // no listener, it's automatically removed } }
version #10384, modified 2011-04-02 12:30:58 by MrCheater