1

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 Answers 2

5

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);
}
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.