views:

56

answers:

2

In as3, I am adding event listener and then attaching the anonymous function to it:

myBox.addEventListener(MouseEvent.ROLL_OVER, function(e:MouseEvent):void { Alert.show(count, 'Alert Box'); );

Now this whole piece of code is looped n times. Now, I have n myBoxes and whenever I roll my mouse over the box, it should alert the name. But, what I see is that the last value of count is used by each box.

How can I pass parameter or value to the anonymous function? ( as roll over , I believe, expects only one variable)

+2  A: 

You need to create a new scope by executing a function:

for (var i:int = 0; i<10; i++)
{
    (function(count:int):void
    {
        myBox.addEventListener(MouseEvent.ROLL_OVER, 
            function(e:MouseEvent):void { Alert.show(count, 'Alert Box'); });
    })(i);
}
Richard Szalay
+1  A: 

Rather than relying on an index, wouldn't it be simpler (and better) to get the currentTarget of the event and get the value of one of its members?

myBox.addEventListener(MouseEvent.ROLL_OVER,
function(e:MouseEvent):void
{
  Alert.show(UIComponent(e.currentTarget).name, 'Alert Box');
);

If you absolutely have to reference the index, you could get that by

UIComponent(e.currentTarget).parent.getChildIndex(e.currentTarget)

And, now that I think of it, you don't even have to make this an anonymous function at all if you use the event model.

Robusto
yea, thats right !!! :)