AS3 - 仅触发一次的事件侦听器
我正在寻找一种添加 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 );
有人知道如何做到这一点吗?
任何帮助将不胜感激。
(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)
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.
I found this function (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 );
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)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我发现不使用静态或用噪音弄乱代码的最干净的方法是定义一个全局函数(在名为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:
Then you can listen for events like so:
我没有尝试过,但您可以将 EventUtil 静态方法转换为标准方法并扩展对象中的类。
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.