1

I have a container with many images. Instead of adding a listener for click and other mouse events on each of the images, I would like to only listen for those events on the parent of the image.

Is that possible?

Francisc
  • 77,430
  • 63
  • 180
  • 276

2 Answers2

7
container.addEventListener(MouseEvent.CLICK, clickHandler);
private function clickHandler(e:MouseEvent):void {
  trace(e.currentTarget); // references container
  trace(e.target); //references container's child or container itself depending on what has been clicked 
}
package
  • 4,741
  • 1
  • 25
  • 35
1

If i am understanding your question correctly, that is totally possible. So assuming you have something like:

parent.addChild(new Child());
parent.addChild(new Child());
parent.addChild(new Child());
parent.addChild(new Child());

Then you should be able to bind the event listener to the parent thusly:

parent.addEventListener(MouseEvent.CLICK, handleClick);

and then your handler should look something like

private function handleClick(e:MouseEvent) {
    // cast the target of the event as the correct class
    var clickedChild:Child = Child(e.target); 

    // Do whatever you want to do.
}

You can also combine this with the useCapture argument of addEventListener to attach the event on the capturing side of the event rather than the bubbling side. And also use the .stopPropagation() method on the Event to stop any other event handlers from firing as well...

But its difficult to say if you need to use those without knowing more about what you are trying to do. But hopefully that will give you a push in the right direction.

J. Holmes
  • 18,466
  • 5
  • 47
  • 52