Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
586 views
in Technique[技术] by (71.8m points)

flash - How do you bind a variable to a function in as3

I have this 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...