繁体   English   中英

如何将变量绑定到 as3 中的 function

[英]How do you bind a variable to a function in as3

我有这个代码:

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

如何将工具的值绑定到 function 以便在回调时可以访问?

您必须在 function 中使用 function 才能正确绑定 scope。 这是一种在 AS3 中的 hack。 如果你能帮上忙,最好不要把 go 掉进那个兔子洞。 如果你必须,虽然...

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 ......因此,您不仅可以接受 scope 参数,还可以传递您的 id、计数、当前 state 或其他.

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

尝试这个。

for each(var tool in tools){
  tool.addEventListener(MouseEvent.MOUSE_DOWN, toolFunction )
}

function toolFunction (e:MouseEvent){
  trace(e.currentTarget)
}

再次阅读问题标题后,我意识到,您需要的是自定义事件或:

for each(var tool in tools){
      tool.addEventListener(MouseEvent.CLICK,
              function(e:MouseEvent){toolFunction (e, "another param")},
              false, 0, true);
    }

    function toolFunction (e:MouseEvent,anotherParam:String){
      trace(e.currentTarget)
      trace(anotherParam) //output "another param"
    }

试着做:

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

您不能在循环内嵌套函数,function 调用的参数在循环的所有迭代中将具有相同的值,并且该值将来自最后一次迭代。 有一些技巧可以处理这个问题,但这不是好的编码实践,并且将来很难修改它。

你需要做的是更多的OOP风格。

由于工具 class 显然是自定义的,因此您需要对其进行修改以保存您将来谈论的值或任何引用。
基本上,如果您需要传递与该 object 相关的值,那么只需将该值作为 class 工具的属性即可。

使用 as3 信号

http://www.peterelst.com/blog/2010/01/22/as3-signals-the-best-thing-since-sliced-bread/

它可以很好地解决您的问题。 一旦我尝试了信号,我就不能 go 回来。 比as3中的事件系统好多了

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM