ActionScript 3.0 为事件处理程序使用闭包 [英] ActionScript 3.0 using closures for event handlers

查看:23
本文介绍了ActionScript 3.0 为事件处理程序使用闭包的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试这样做:

root.addEventListener("click", 
   function () 
   { 
      navigateToURL(ClickURLRequest,"_self"); 
   });

它确实添加了事件侦听器.我喜欢使用闭包,因为它们在这种情况下效果很好,

And it does add the event listener. I like using closures because they work well in this situation,

然而,移除事件监听器需要引用原函数,而且由于我使用了匿名闭包,它不起作用,我尝试了:

however, removing the event listener requires a reference to the original function, and since I used an anonymous closure, it does not work, I tried:

   root.removeEventListener("click", 
       function () 
       { 
          navigateToURL(ClickURLRequest,"_self"); 
       });

以及:

   root.removeEventListener("click", function () {} );

我发现它起作用的唯一方法是放弃匿名闭包并将事件侦听器指向预先存在的函数:

The only way I found it would work was to ditch the anonymous closure and point the event listeners at a pre-existing function:

 function OnClick (e:Event)
 {
     navigateToURL(ClickURLRequest,"_self");
 }

 root.addEventListener("click", OnClick);
 root.removeEventListener("click", OnClick);

有谁知道在事件处理程序中使用匿名闭包的方法,同时仍然保留删除它们的能力?

Does anyone know a way to use anonymous closures for event handlers while still retaining the ability to remove them?

推荐答案

这是删除我在生产项目中使用的事件侦听器的通用方法

Here's a generic way of removing event listeners that i have used on production projects


addEventListener
(
    Event.ACTIVATE, 
    function(event:Event):void
    {
        (event.target as EventDispatcher).removeEventListener(event.type, arguments.callee)             
    }
)

这篇关于ActionScript 3.0 为事件处理程序使用闭包的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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