views:

49

answers:

3

I have a button labeled 'blueButton' and I'd like to use an anonymous function to handle the click, like so:

blueButton.addEventListener(MouseEvent.CLICK, function(event:MouseEvent):void {
 trace( "-----click detected-----" );
 // now do other stuff
});

Problem is, the click handler is called multiple times per click. The number of times called seems to be random (sometimes 2, sometimes 4, sometimes 3 etc). could I be missing something in my code, or maybe I set up the button wrong?

also I noticed that it seems to always get called once on the first click. After the first click is when it starts getting called additional times, maybe that has something to do with it?

thanks in advance for any help

A: 

Where is blueButton.addEventListener being called from? It is possible that the line is being called multiple times, which could then add multiple listeners, especially if it's added after some view state onShow code for example. Try adding trace("---- adding event listener ----" ) just above blueButton.addEventListener and make sure that only shows up once.

Also, have you tried you code with nothing but the trace() statement in it? Is it still a problem then? You can split the different by removing all other code in the event listener. There is a small chance the "other stuff" could be triggering code to run that adds the button event listener again.

Nick
A: 

I'd try to fix this doing 2 things:

1) Make sure you set blueButton.mouseChildren = false. On certain mouse events, if the specified DisplayObject has other DisplayObject children inside of it, flash will dispatch the mouse event for each child.

2) Don't use anonymous functions because Flash acts a bit weird when you use them occasionally. I've had the same problem as you before and once I stopped using the anonymous function the problem went away.

Fox
A: 

You could also try

event.stopImmediatePropagation;
PatrickS