AS3 - 仅触发一次的事件侦听器 [英] AS3 - Event listener that only fires once

查看:136
本文介绍了AS3 - 仅触发一次的事件侦听器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种方法来添加一个EventListener,它会在第一次触发后自动删除它,但是我无法想像这样做。

I'm looking for a way to add an EventListener which will automatically removes itself after the first time it fires, but I can't figure a way of doing this the way I want to.

我发现这个功能( here ):

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


但不必写: / p>


But instead of having to write :

EventUtil.addOnceEventListener( dispatcher, eventType, listener );

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

I would like to use it the usual way :

dispatcher.addOnceEventListener( eventType, listener );


有人知道如何做到这一点吗?

任何帮助将被大大的欣赏。




(我知道Robert Penner的信号可以这样做,但是我不能使用它们,因为这意味着很多代码重写,我现在的项目无法承受)


Has anybody got an idea of how this could be done?
Any help would be greatly apprecitated.


(I know that Robert Penner's Signals can do this, but I can't use them since it would mean a lot of code rewriting that I can't afford for my current project)

推荐答案

我发现最简洁的方式,而不使用静态或者弄乱你的代码是为了定义一个全局函数(在一个名为removeListenerWhenFired.as的文件中),如下所示: / p>

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

这篇关于AS3 - 仅触发一次的事件侦听器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆