PDA

View Full Version : a fun problem with MouseEvent :O



artheus
October 7th, 2009, 08:05 AM
Hey!

I just ran in to a little funny problem with MouseEvent!

What I did was to make a image-gallery class, and in that make a eventlistener for MouseEvent.Click for every individual image. And in the handler i've done a dispatchEvent. like this :



for(var i:int = 0; i < numImages; ++i) {
image[i].addEventListener(MouseEvent.CLICK, mouseClickHandler);
}

private function mouseClickHandler(e:MouseEvent):void
{
dispatchEvent(e);
}


And then in the main-class I've made a listener for that, like this



imageGallery.addEventListener(MouseEvent.CLICK, mouseClickHandler);

private function mouseClickHandler(e:MouseEvent):void
{
trace(e.target);
}



And what I get is multiple targets!



[object imageGallery]
[object image]


How do I make this access only one of these targets!? These don't work:




trace(e.target[0]);
trace(e[0].target);



HELP!?

//Artheus

_kp
October 7th, 2009, 08:33 AM
I think you got the trace wrong, if it were an array it would be a single line ;)

I guess when you click an image both the image's and the gallery's event is triggered (because image is child of gallery(?)). It traces two different targets since you did use .target instead of .currentTarget

If I'm right dispatchEvent(e); doesn't do anything because the event is passed to the main class which doesn't have a listener for it.

The Funtastic
October 7th, 2009, 08:38 AM
Sounds like and problem with bubbling,

when dispatching the event try:

dispatchEvent(new MouseEvent(MouseEvent.CLICK, false));

or if that doesn't work try this in the listener:

var myTarget:Image;

if (e.currentTarget is Image){
myTarget = e.currentTarget
}

IQAndreas
October 7th, 2009, 08:44 AM
Also, you shouldn't be able to dispatch the same event twice. You need to clone it first.
this.dispatchEvent(e.clone());

Don't ask me why, that's just how it's set up.

The Funtastic
October 7th, 2009, 09:21 AM
Also, you shouldn't be able to dispatch the same event twice. You need to clone it first.
this.dispatchEvent(e.clone());

Of course! I didn't think of that. The problem is that the event is dispatched by Image inside imageGallery and hence the Image is the target. When imageGallery dispatches the SAME event ImageGallery becomes the target too.

Felixz
October 8th, 2009, 04:17 PM
You are getting two events, one dispatched automatically and one dispatched by you.
MouseEvents bubble so you do not need to redispatch them; see currentTarget and target properties.