你怎么一个变量绑定到AS3功能你怎么、绑定、变量、功能

2023-09-08 12:20:16 作者:橘裏〓路亽

我有这个code:

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

如何绑定工具给函数的值,使得它在回调访问?

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

推荐答案

您必须使用一个函数的函数内部正确地绑定的范围。这是一种在AS3一个黑客攻击。最好不要走这兔子洞,如果你能帮助它。如果你一定要,但...

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.

EDIT2:不过问自己这个问题。您将如何删除事件监听器?这就是我说要避免这种兔子洞完全的最大原因。这是可能的,但它比用解决这个问题,而不是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.