簡體   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