AS3 - Event listener that only fires once

微笑、不失礼 提交于 2019-12-03 15:30:05

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
            }
        )
    )

I've not tried it, but you could just turn the EventUtil static method into a standard method and extend the class in your object.

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);
functionadd.addEventListener(COMPLETE,functionremove);

functionremove()
{
    runevent();
    functionadd.removeEventListener(COMPLETE,functionremove);
}
function runevent()
{
   trace('Hello');
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!