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

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

问题描述

我正在寻找一种方法来添加一个事件监听它的第一次闪光后会自动删除自身,但我不知道这做我想要的方式的一种方式。

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.

我发现这个功能(<一href="http://$c$c.google.com/p/asphalt2/source/browse/trunk/asphalt2/src/asphalt2/util/EventUtil.as?r=457">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);
    }
}


不过,而不必写:


But instead of having to write :

EventUtil.addOnceEventListener( dispatcher, eventType, listener );

我想用它通常的方式:

I would like to use it the usual way :

dispatcher.addOnceEventListener( eventType, listener );


有没有人得到的是如何能够做到这一点的想法?
任何帮助将大大AP precitated。


(我知道,罗伯特·彭纳的信号可以做到这一点,但我不能使用它们,因为这将意味着一个很多code重写,我无法承受我当前的项目)


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)

推荐答案

我觉得最干净的方法,而不使用静态或搞乱了你的code噪音是定义一个全局函数(在一个名为removeListenerWhenFired.as)像这样:

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天全站免登陆