How to create custom MouseEvent.CLICK event in AS3 (pass parameters to function)?

Posted by fromvega on Stack Overflow See other posts from Stack Overflow or by fromvega
Published on 2009-01-08T23:52:18Z Indexed on 2011/01/03 0:54 UTC
Read the original article Hit count: 141

Filed under:
|
|
|
|

Hello,

This question doesn't relate only to MouseEvent.CLICK event type but to all event types that already exist in AS3. I read a lot about custom events but until now I couldn't figure it out how to do what I want to do. I'm going to try to explain, I hope you understand:

Here is a illustration of my situation:

for(var i:Number; i < 10; i++){
    var someVar = i;
     myClips[i].addEventListener(MouseEvent.CLICK, doSomething);
}

function doSomething(e:MouseEvent){ /* */ }

But I want to be able to pass someVar as a parameter to doSomething. So I tried this:

for(var i:Number; i < 10; i++){

    var someVar = i;
    myClips[i].addEventListener(MouseEvent.CLICK, function(){
        doSomething(someVar);
    });
}

function doSomething(index){ trace(index); }

This kind of works but not as I expect. Due to the function closures, when the MouseEvent.CLICK events are actually fired the for loop is already over and someVar is holding the last value, the number 9 in the example. So every click in each movie clip will call doSomething passing 9 as the parameter. And it's not what I want.

I thought that creating a custom event should work, but then I couldn't find a way to fire a custom event when the MouseEvent.CLICK event is fired and pass the parameter to it. Now I don't know if it is the right answer.

What should I do and how?

© Stack Overflow or respective owner

Related posts about flex

Related posts about flash