Duplicate event listeners
Posted: 12/08/08
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
Popular categories:
Recent posts:
- Mac OS find files using regex
- ADB device driver won't install
- Eclipse: An error has occurred. See the log file .metadata/.log
- Updated blinkbox iPad app
- Nexus 7 doesn't appear in adb devices list
- Improve the keyboard in the Samsung ICS update
- 403 Forbidden error on Mac web server
- Getting error with manually created NIB?
- Adding/removing items from PATH on Mac
- Presenting at Flash Oxford
- more...
Publications:
Places you'll find me:
Archive:
- March 2024
- February 2024
- January 2024
- December 2023
- November 2023
- October 2023
- September 2023
- August 2023
- July 2023
- June 2023
- May 2023
- April 2023