AS3 Listener Help

Subscribe to AS3 Listener Help 3 posts

avatar for JRaz JRaz 12 posts
Flag Post

If I understand correctly then to call a function when an object is clicked i would use the following code.

myObject.addEventListener(MouseEvent.CLICK,myFunction);

However what i actually have is an array of objects and i want to call a function with the index of that array passed in as a parameter so that i know which of the objects was clicked, what I would like to do is something like this.

for(a=0;a<100;a++){
myObject[a].addEventListener(MouseEvent.CLICK,myFunction(a));
}

But that doesn’t work, so if someone could suggest a way to achieve what I am trying to do that would be greatly appreciated.

 
avatar for Moonkey Moonkey 1007 posts
Flag Post

Do you know about the currentTarget property of Events? It gives you a reference to the object that dispatched the event.

For example,


function myFunction(event:Event) {
var myObject:MovieClip = event.currentTarget as MovieClip;
// do stuff with myObject
}

If you really need an index as opposed to a direct reference, you’d probably have to store it within the object itself and retrieve it that way.

 
avatar for JRaz JRaz 12 posts
Flag Post

Thanks Moonkey, based on what you said I gave each object a private index attribute, a public index getter funtion and then used currentTarget.getterFunction to retrieve the index.