I want to make in loop set of buttons, and add to them some events, but anonymous functions is the same. I write example code:
for(var i:int=0;i<5;i++)
{
var button:SimpleButton = new SimpleButton(...);
...
button.addEventListener(MouseEvent.CLICK, function(event:MouseEvent):void
{
trace(i);
});
}
...
And I want to trace 0,1,2,3.. from click buttons instead of 4,4,4,4 .. Do you know how can I make this ?
An anonymous function is a function with no name which can be used once they're created. The anonymous function can be used in passing as a parameter to another function or in the immediate execution of a function.
An anonymous function is a function that is not stored in a program file, but is associated with a variable whose data type is function_handle . Anonymous functions can accept multiple inputs and return one output. They can contain only a single executable statement.
Anonymous Function is a function that does not have any name associated with it. Normally we use the function keyword before the function name to define a function in JavaScript, however, in anonymous functions in JavaScript, we use only the function keyword without the function name.
An anonymous function is a function that was declared without any named identifier to refer to it. As such, an anonymous function is usually not accessible after its initial creation.
The problem you are running into is that ActionScript does not support closures.
In other words, the variable i
does not get copied into it's own context per function. All functions refer to the same instance of i
.
More information here: http://flex.sys-con.com/node/309329
In order to do this, you need a function that generates a function:
public function makeFunction(i:int):Function {
return function(event:MouseEvent):void { trace(i); }
}
Now, you create new instances of the function with their own context:
button.addEventListener(MouseEvent.CLICK, makeFunction(i));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With