ActionScript 3 Event Listeners Tips & Tricks
The event framework or EventListeners in ActionScript 3 is one of the best features that AS3 has, here a some tips and tricks that I have found very usefully.
Useing WeakReference:
In AS3 objects gets garbage collected if there are no references to them. If you remove your object where an event listener is added but if the object is still being referenced somewhere else it will not be garbage collected given you the possibility of having memory leakage (strong memory references). If you set your event listener with weak memory references the event listener gets garbage collected when the object it’s added to gets removed.
movieClip.addEventListener(MouseEvent.CLICK, true, clickHandler);
Priority:
If you didn’t know event listeners don’t work simultaneously sometimes they conflict with each other to fix this you may want to make sure that certain event listener have a higher priority then others.
movieClip.addEventListener(MouseEvent.CLICK, clickHandler, false, 0, true);
One Listener Function, Multiple Events:
Sometimes you may want to save code or just write nicer and cleaner code a best practice for this is using one listener function for multiple events.
if(event.type == "mouseDown"){
trace("Down");
}else{
trace("Up");
}
}
movieClip.addEventListener(MouseEvent.MOUSE_DOWN, handler);
movieClip.addEventListener(MouseEvent.MOUSE_UP, handler);
One Event Listener, Multiple Objects:
So this is one of my favorite things in AS3, not only does it save time but its very usefully when you have large navigation menus. What you want to do is have a container movie clip which holds all the your other movie clip or you navigation, you will give that movie clip the event listener and use the event.target.name to identity which movie clips are being clicked on.
if(event.target.name == "movieClip1"){
trace("movieClip");
}
if(event.target.name == "movieClip2"){
trace("movieClip2");
}
if(event.target.name == "movieClip3"){
trace("movieClip3");
}
}
container.addEventListener(MouseEvent.CLICK, clickHandler);
Cleanup Up Multiple Event Listeners:
Sometimes times you need to remove multiple event listeners at once, this function overrides the standard addEventListener function, storing all added event listeners including parameters in an array. Once this is done you would call target.clearEvents() to remove all event listeners on that target.
function addEventListener (type:String, listener:Function, useCapture:Boolean=false, priority:int=0, useWeakReference:Boolean=false):void { super.addEventListener (type, listener, useCapture, priority, useWeakReference);
myArrayListeners.push({type:type, listener:listener, useCapture:useCapture});
}
function clearEvents():void {
for (var i:Number=0; i < myArrayListeners.length; i++) {
if (this.hasEventListener(myArrayListeners[i].type)) {
this.removeEventListener(myArrayListeners[i].type,
myArrayListeners[i].listener);
}
}
myArrayListeners=null;
Using Key Codes:
On your keyboard every key has a certain number; a key code this is very useful for games and interactive kiosk’s You can fins a list of key codes here
if(event.keyCode == 38){
trace("You just pressed the arrow up key");
}
if(event.keyCode == 40){
trace("You just pressed the arrow down key");
}
}
stage.addEventListener(KeyboardEvent.KEY_DOWN, keyDownHandler);











This site rocks!
Hey good stuff…keep up the good work! :)
Very useful tips, especially the one about one event listener, multiple objects. Thank you.
Great stuff! Thanks :)
I tried your method of cleaning up event listeners, but it didn’t work.
Is there any specific implementation required?
Hi Seleneue, did you make sure to push all your event listeners to an array, also did you run the clearEvents() function. If you can’t get it to work send me the files I will try to take a look.
congrats! very helpful stuff… thnx
absolutely kewl!!!! super helpful. thank you
Finally, someone gives the shortcut to us noobs for one event listener, multiple objects. AND I actually got it to work! Thanks…
There are two errors:
First:
movieClip.addEventListener(MouseEvent.CLICK, true, clickHandler);
This call is wrong, should be:
movieClip.addEventListener(MouseEvent.CLICK, clickHandler, false, 0, true);
If you want to use capture and weak reference.
And here:
myArrayListeners.push({type:type, listener:listener});
You should add useCapture to the array, because it’s neccesary to delete correctly the listener. It should be:
myArrayListeners.push({type:type, listener:listener, useCapture:useCapture});
and should be used in this way:
for (var i:Number=0; i < myArrayListeners.length; i++)
{
this.removeEventListener(myArrayListeners[i].type,
myArrayListeners[i].listener, myArrayListeners[i].useCapture);
}
note We don’t need to check hasEventListener because “if there is no matching listener registered with the EventDispatcher object, a call to this method has no effect.”
greets!
Thanks for your code but in my application i have 4 actioscipt files,so where to call this function is not clearly understood,
all actionscript files are related to each other.
Having an issue, hoping you have some insight:
object.addEventListener(event, handler);
object.addEventListener(event, handler2);
I have a button [object]. I add two event handlers for the same event. The first handler modifies the state of the button, while the second handler makes an http call.
Only one event handler is being called (and it appears to be a random race condition).
Solution?
Cheers
what type of event are you calling? If your calling an click event you can only have one. You might want to try the following
addEventListener(MouseEvent.MOUSE_OUT, mouseOutHandler);
addEventListener(MouseEvent.MOUSE_OVER, mouseOverHandler);
For changing the state of the button and a click event for the http call
addEventListener(MouseEvent.CLICK, clickHandler);
http://tinyurl.com/2u5fxjh
ActionScript 3 Event Listeners Tips & Tricks | Almog Design
GREAT stuff !!
However Using WeakReference:
movieClip.addEventListener(MouseEvent.CLICK, true, clickHandler);
Should be
movieClip.addEventListener(MouseEvent.CLICK, clickHandler,true);
thnx…..i find it very useful and informative.
http://www.almogdesign.net/blog/actionscript-3-event-listeners-tips-tricks/
#ActionScript 3 Event Listeners Tips & Tricks http://twurl.nl/nxgrxp
From all the blogs and posts i went through online, this page goes straight to the point and tells me exactly what i need.
Don’t know why i hadn’t thought about storing the listener properties in an array before then cleaning up later, it’s a simple but excellent idea though.
Thank you for posting this info.
Some really good ventListener tips and tricks #AS3 http://bit.ly/d6DZTX
I am having a problem removing my event listeners.
The setup on my site is that there is a bar the flips 3d. This is called conTop. It contains 2 movieclips sidea and sideb. Sideb cntains a nav of 3 buttons menu, drinks, specials. When you click on menu (or any of the buttons) it throws an error and I cant move forward.
When you click on menu it is supposed to take you to the next frame, but no luck
here is my code:
stop();
import fl.transitions.Tween;
import fl.transitions.easing.Strong;
import fl.transitions.TweenEvent;
import flash.display.MovieClip;
import flash.events.MouseEvent;
conTop.sidea.addEventListener(MouseEvent.MOUSE_OVER,onflip);
conTop.sideb.addEventListener(MouseEvent.MOUSE_OVER,onflip);
addEventListener(Event.ENTER_FRAME,loop);
var isStill:Boolean=true;
var arraytween:Array = new Array();
function onflip(e:Event) {
if (isStill) {
arraytween.push(new Tween(conTop,’rotationX’,Strong.easeOut,conTop.rotationX,conTop.rotationX+180,1,true));
arraytween[0].addEventListener(TweenEvent.MOTION_FINISH,reset);
//conTop.sideb.gotoAndPlay(“start”);
isStill=false;
}
}
function reset(e:Event) {
isStill=true;
arraytween=[];
}
function loop(e:Event) {
// trace(conTop); // Should trace null when you get error
if (conTop.rotationX>=90 && conTop.rotationX=360) {
conTop.rotationX=0;
}
}
conTop.sideb.menuBtn.addEventListener(MouseEvent.CLICK, moveNFrame);
function moveNFrame (e:MouseEvent) {
gotoAndStop(“worked”);
removeEventListener(Event.ENTER_FRAME,loop);
//arraytween[0].removeEventListener(TweenEvent.MOTION_FINISH,reset);
}
/*topExt.drinkBtnEx.addEventListener(MouseEvent.CLICK, maybeSo)
function maybeSo (e:MouseEvent) {
gotoAndPlay(“workedAgain”);
topExt.drinkBtnEx.removeEventListener(MouseEvent.CLICK, maybeSo)
}*/
@kellyb what errors are you getting?
Im trying to do exactly what you explained on “One event listener, Multiple objects”, but it’s not working…
I have a container which has lots of buttons in it… I want the container to detect any roll over on any button, so in the container AS file, I add an event listener like:
this.addEventListener(MouseEvent.ROLL_OVER, _button_Roll);
In the event listener function, I trace the event.target.name, but it is returning the container name, not the button which generated the event name…
Is there any easy way of detecting which button triggered the event, without adding an event listener for each button?
Hi @pep_castefa
It’s designed to work on mouse click and not mouse rollover, for mouse rollover try the following event.child.target.name or event current target
Thank you for your response…
I have tried event.child.target.name but gave an error… the MouseEvent class (nor the Event class) doesn’t have a child property.
If I try e.currentTarget, it returns the container, but not the button in the container…
@pep_castefa have you tried getChildAt or getChildByName?
http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/flash/display/DisplayObjectContainer.html
I don’t understand… I get, from the container of the buttons, the event that the mouse has rolled over one of its buttons, but I don’t get the information of which button… I just get the information that the mouse rolled over one of them… I would need to get on which of them.
I have solved it making the container listen to all of its buttons, and when it gets a roll over, the container sends an event specifying which button was rolled over, so the receiver has all the information… but I preferred your solution because it was more clean.
@pep_castefa, Your main event listener is listing to that container not the children or mouse buttons. If you want to listen for mouse buttons which are the children you will need an if statement inside the main function that checks.
[...] http://www.almogdesign.net/blog/actionscript-3/actionscript-3-event-listeners-tips-tricks/ [...]
These are valuable tips.
I’m a beginner at AS. i can usually get around building a lot of stuff with very little logic. This is a good way to teach people to integrate logic in real world examples.
Awesome tips :) much appreciated.
one thing, when trying to use the clean up multiple events technique, i am getting an ‘incompatible override’ error. any ideas?
About AS3 and listeners. A must read! http://t.co/wg250VS
About AS3 and listeners. A must read! http://t.co/wg250VS
i’m not a heavy as3 user, but am finding that there’s a lot of confusing stuff for me to do, in order to create a simple button action that effects other symbols in its “family tree” (in this case, its “parent” and — what i’ll term — its “great uncle”). i read something, which explains approximately that cs3 is unable to enact button actions of nested symbols. it goes on to explain that i need to use “trace(MovieClip( …” to let flash know that it’s dealing with movies and not objects… or something like that.
anyway, i don’t understand all the meta-language being spoken here. i just want to get this to work the way i used to be able to do when i used as1 (it’s been AHWILE). can someone please simply tell me what code to write and where to put it? i believe it’s just a simple thing, but i just don’t have access to that knowledge or the background to understand it.
i’ll give you the details of what i’m doing, so that you have a reference to work with. first, here’s the hierarchical structure of the symbols in question:
Scene 1 (main time line)
– mb (movie clip)
+ mbon (movie clip)
^ tog (the button in question)
+ mbse (movie clip)
– m1
and here’s the basic script that i’m using in frame one of the main timeline:
root.mb.mbon.tog.addEventListener(MouseEvent.CLICK,
fl_ClickOnToSe);
function fl_ClickOnToSe(event:MouseEvent):void
{
root.s1.gotoAndStop(“se”);
root.mb.mbse.gotoAndStop(“on”);
root.mb.mbon.gotoAndStop(“off”);
}
and here’s what i though i was supposed to do with this “trace” command at the top of the scripting code:
trace(MovieClip(root).mb);
trace(MovieClip(root).s1);
trace(MovieClip(root.mb).mbon);
trace(MovieClip(root.mb).mbse);
trace(SimpleButton(root.mb.mbon).tog);
i meant to include “uncle” with “parent” and “great uncle” in the above explanation, incase anybody didn’t already get that.
oops! and here’s the hierarchical structure again, with better visual reference (sorry, the screen displays this differently than i typed it)
– mb (movie clip)
…+ mbon (movie clip and “parent” to “tog”)
……^ tog (the button in question)
…+ mbse (movie clip and “uncle” to “tog”)
– m1 (movie clip and “great uncle” to “tog”)
ActionScript 3 Event Listeners Tips & Tricks | Almog Design http://t.co/qi6cIyWa
Hi, I have these thumbnails, and an arrow as a button to scroll through them, I’m using gotoandplay(and the frramenumber) to go to the image, all the image display, but when I wanna go to the begging ie replay these images or review them from the beggining I cnt it doesn’t do anything…pls help
Hey
I am using your method for event listeners with multiple movie clips and the first time I used it it worked perfect, so thanks for that.
Since that first time though it hasn’t worked since. In the past I can’t remember what the issue was but every ‘part’ of my image had a different instance name and I couldn’t check against the name that I gave each movieclip.
Currently I am working on a project and I am using-
trace(e.currentTarget.name);
to trace the names of my movie clips which are all unique and not similar in anyway. Each of them returns “root1″ in my output box.
I’d be very greatful if you could clear this up and let me know what I am doing wrong.