Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating anonymous functions in loop with not the same arguments

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 ?

like image 651
onio9 Avatar asked Dec 25 '10 13:12

onio9


People also ask

Does anonymous function accept parameters?

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.

What makes an anonymous function so unique?

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.

How do you create an anonymous function?

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.

Does anonymous functions allow creation of functions without specifying their 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.


1 Answers

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));
like image 167
Brian Genisio Avatar answered Nov 03 '22 00:11

Brian Genisio