I want to target multiple buttons and get different value by clicking different button.
Suppose there are 3 buttons: “button01”, “button02, “button03”.
This is my code:
var targetArr:Array = ["button01","button02","button03"];
for (var i:int = 0; i < targetArr.length; i++)
{
var target = getChildByName(targetArr[i]);
target.addEventListener(MouseEvent.CLICK, targetFunc);
function targetFunc(event:MouseEvent):void
{
trace(i);
}
}
Instead of getting different value by clicking different button, I constantly get “3” as the value.
I want: clicking “button01” will get “0” as the value, clicking “button02” will get “1” as the value, and clicking “button03” will get “2” as the value. How to do it?
You are almost there! What is happening is that the reference to
iis being shared by all of your event handlers. What you want is a distinctive copy of the value ofiwhen the event handler is registered.To do this, you can create a new closure for each iteration of your loop.
What is happening now is that we are passing the particular value of
ito a helper function that then returns the event handler function. This way we are using a closure to close over the particular value ofiat the time we register the handler.EDIT: Here is another slightly different way of arranging things. For each iteration of your loop, you could call a function that registers the handler: