How do you bind a variable to a function in as3

后端 未结 5 1487
孤独总比滥情好
孤独总比滥情好 2020-12-21 16:08

I have this code:

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


        
5条回答
  •  情书的邮戳
    2020-12-21 16:53

    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));
    }
    

    EDIT: 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: 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.

提交回复
热议问题