11

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 ?

onio9
  • 111
  • 4

1 Answers1

20

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));
Brian Genisio
  • 47,787
  • 16
  • 124
  • 167