Duplicate event listeners

Posted: 12/08/08

An image of Duplicate event listeners

I got asked the other day what happens if you already have a listener assigned to an object and then reassign it again. Wondering under what circumstances this might be an issue, they told me of times when a listener may have been dynamically assigned to a group of objects, then removed from a subset of them. The concern was that more and more listeners could be assigned, creating rogue callbacks.

The simple answer is that if a registration of both the event type and callback are already assigned, there won't be duplication and multiple callbacks.

I then noticed that a few Flash devs out on the Internet have been getting their knickers in a twist about the same thing. I came across this code:

if (! Next_btn.hasEventListener(MouseEvent.MOUSE_UP))(

Next_btn.addEventListener(MouseEvent.MOUSE_UP,function(evt:MouseEvent):void { nextFrame(); }));

if (! Back_btn.hasEventListener(MouseEvent.MOUSE_UP))(

Back_btn.addEventListener(MouseEvent.MOUSE_UP,function(evt:MouseEvent):void { prevFrame(); }));

The issue above is that the listener function is being dynamically generated each time the listener is being added; whereas if the function existed outside of the registration, the duplication would be picked-up by the player runtime and prevented.

In the basic example below I have a MovieClip object on the stage with the instance name 'mc'. I assign a listener of type 'MouseEvent.CLICK' with the callback 'onMouseClick' three times, and then assign a listener with the same type but a different callback.

mc.addEventListener( MouseEvent.CLICK, onMouseClick );

mc.addEventListener( MouseEvent.CLICK, onMouseClick );

mc.addEventListener( MouseEvent.CLICK, onMouseClick );

mc.addEventListener( MouseEvent.CLICK, onMouseClick2 );

function onMouseClick( e:MouseEvent ) :void

{

trace( "1st call-back was triggered" );

}

function onMouseClick2( e:MouseEvent ) :void

{

trace( "2nd call-back was triggered" );

}

When I click the MovieClip on the stage, the following is traced-out:

1st call-back was triggered

2nd call-back was triggered

Keywords for this post: actionscript 3, event listener, events, flash, flex, duplicate listener