5

我正在寻找一种添加 EventListener 的方法,该 EventListener 将在第一次触发后自动删除,但我无法按照我想要的方式执行此操作。

我找到了这个功能(在这里):

public class EventUtil
{
    public static function addOnceEventListener(dispatcher:IEventDispatcher,eventType:String,listener:Function):void
    {
         var f:Function = function(e:Event):void
         {
              dispatcher.removeEventListener(eventType,f);
              listener(e);
          }
          dispatcher.addEventListener(eventType,f);
    }
}


但不必写:

EventUtil.addOnceEventListener( dispatcher, eventType, listener );

我想以通常的方式使用它:

dispatcher.addOnceEventListener( eventType, listener );


有没有人知道如何做到这一点?
任何帮助将不胜感激。


(我知道 Robert Penner 的Signals可以做到这一点,但我不能使用它们,因为这意味着我目前的项目负担不起大量代码重写)

4

3 回答 3

11

I find the cleanest way without using statics or messing up your code with noise is to defining a global function (in a file called removeListenerWhenFired.as) like so:

package your.package
{
    import flash.events.Event;
    import flash.events.IEventDispatcher;

    public function removeListenerWhenFired(callback:Function, useCapture:Boolean = false):Function
    {
        return function (event:Event):void
        {
            var eventDispatcher:IEventDispatcher = IEventDispatcher(event.target)
            eventDispatcher.removeEventListener(event.type, arguments.callee, useCapture)
            callback(event)
        }
    }
}

Then you can listen for events like so:

import your.package.removeListenerWhenFired

// ... class definition

    sprite.addEventListener(MouseEvent.CLICKED, 
        removeListenerWhenFired(
            function (event:MouseEvent):void {
                ... do something
            }
        )
    )
于 2010-03-22T16:59:14.680 回答
2

我没有尝试过,但是您可以将 EventUtil 静态方法转换为标准方法并在对象中扩展该类。

public class OnceEventDispatcher
{
    public function addOnceEventListener(eventType:String,listener:Function):void
    {
         var f:Function = function(e:Event):void
         {
              this.removeEventListener(eventType,f);
              listener(e);
          }
          this.addEventListener(eventType,f);
    }
}

public class Example extends OnceEventDispatcher
{


}

var ex:Example = new Example();
ex.addOnceEventListener(type, func);
于 2010-03-19T13:45:27.690 回答
1
functionadd.addEventListener(COMPLETE,functionremove);

functionremove()
{
    runevent();
    functionadd.removeEventListener(COMPLETE,functionremove);
}
function runevent()
{
   trace('Hello');
}
于 2013-06-14T06:02:15.273 回答