as3中如何将变量绑定到函数 [英] How do you bind a variable to a function in as3

查看:29
本文介绍了as3中如何将变量绑定到函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个代码:

for each(var tool in tools){
tool.addEventListener(MouseEvent.MOUSE_DOWN, function(){
    trace(tool); //Always the last tool  
 });
}

如何将 tool 的值绑定到函数以便在回调时可以访问它?

How do I bind the value of tool to the function so that it's accessible on callback?

推荐答案

您必须在函数内部使用函数才能正确绑定作用域.这有点像 AS3 中的 hack.如果你能帮上忙,最好不要掉进那个兔子洞.如果你必须的话...

You have to use a function inside a function to properly bind the scope. It's kind of a hack in AS3. It's better not to go down that rabbit hole if you can help it. If you must, though...

for(var tool:Tool in _tools){
  var getHandler(scope:Tool):Function{
    var t:Tool = scope;
    return function(e:MouseEvent):void{trace(t)}
  }
  tool.addEventListener(MouseEvent.CLICK, getHandler(tool));
}

当然,您需要在处理程序中使用的任何变量也应该传递给 getHandler ......所以不仅仅是接受范围参数,您还需要传递您的 id、计数、当前状态, 或者别的什么.

And of course, any variables you need to work with in the handler should be passed into getHandler as well... so instead of just accepting the scope param, you'd also pass your id, count, current state, or whatever.

但是问自己这个问题.您将如何删除该事件侦听器?这是我说要完全避免这个兔子洞的最大原因.这是可能的,但通常比使用更面向对象的方法来解决这个问题比使用 lambda 函数更麻烦.

But ask yourself this question. How will you remove that event listener? That's the biggest reason I say to avoid this rabbit hole entirely. It's possible, but it's usually more trouble than using a more OOP way of solving this problem than lambda functions.

这篇关于as3中如何将变量绑定到函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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