Blog

If I have a thousand ideas and only one turns out to be good, I am satisfied. Alfred Bernhard Nobel

ActionScript 3 Event Listeners Tips & Tricks

21st August 2009 ActionScript 3, Blog

action-script-iconThe 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.

addEventListener(type:String, listener:Function, useCapture:Boolean = false, priority:int = 0, useWeakReference:Boolean = false):void

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.

 

addEventListener(type:String, listener:Function, useCapture:Boolean = false, priority:int = 0, useWeakReference:Boolean = false):void

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.

 

function handler(event:MouseEvent):void{
    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.

 

function clickHandler(event:MouseEvent):void{
    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.

 

var myArrayListeners:Array=[];

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

 

function keyDownHandler(event:KeyboardEvent):void{
    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);
Share To Deliciious, Digg and More
40
appreciated comments
  1. 1
    Bill Bartmann September 3rd, 2009 on 06:49

    This site rocks!

  2. 2
    Bill Bartmann September 6th, 2009 on 17:47

    Hey good stuff…keep up the good work! :)

  3. 3
    Rob Layton November 15th, 2009 on 19:21

    Very useful tips, especially the one about one event listener, multiple objects. Thank you.

  4. 4
    MichaelJW December 6th, 2009 on 14:17

    Great stuff! Thanks :)

  5. 5
    seleneyue December 7th, 2009 on 08:28

    I tried your method of cleaning up event listeners, but it didn’t work.
    Is there any specific implementation required?

  6. 6
    Almog December 9th, 2009 on 21:46

    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.

  7. 7
    tom335 December 23rd, 2009 on 02:29

    congrats! very helpful stuff… thnx

  8. 8
    Uyanga January 12th, 2010 on 08:33

    absolutely kewl!!!! super helpful. thank you

  9. 9
    JH January 15th, 2010 on 16:15

    Finally, someone gives the shortcut to us noobs for one event listener, multiple objects. AND I actually got it to work! Thanks…

  10. 10
    Enrique January 21st, 2010 on 23:45

    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!

  11. 11
    Abhishek Saxena May 7th, 2010 on 12:57

    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.

  12. 12
    Chad May 21st, 2010 on 08:02

    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

  13. 13
    Almog May 22nd, 2010 on 10:23

    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);

  14. 14
    onion_papa May 27th, 2010 on 21:32

    http://tinyurl.com/2u5fxjh
    ActionScript 3 Event Listeners Tips & Tricks | Almog Design

  15. 15
    Gingebean June 4th, 2010 on 12:24

    GREAT stuff !!

    However Using WeakReference:

    movieClip.addEventListener(MouseEvent.CLICK, true, clickHandler);
    Should be
    movieClip.addEventListener(MouseEvent.CLICK, clickHandler,true);

  16. 16
    Karthick June 16th, 2010 on 15:41

    thnx…..i find it very useful and informative.

  17. 17
    Chris Arendt June 24th, 2010 on 14:20
  18. 18
    Chuck Miller October 6th, 2010 on 13:51

    #ActionScript 3 Event Listeners Tips & Tricks http://twurl.nl/nxgrxp

  19. 19
    Spark October 9th, 2010 on 10:12

    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.

  20. 20
    DizaBlah October 21st, 2010 on 15:40

    Some really good ventListener tips and tricks #AS3 http://bit.ly/d6DZTX

  21. 21
    kellyb March 2nd, 2011 on 22:38

    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)
    }*/

  22. 22
    Almog Design March 4th, 2011 on 15:32

    @kellyb what errors are you getting?

  23. 23
    pep_castefa March 29th, 2011 on 09:30

    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?

  24. 24
    Almog Design March 31st, 2011 on 08:43

    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

  25. 25
    pep_castefa March 31st, 2011 on 09:07

    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…

  26. 26
    Almog Design March 31st, 2011 on 09:11
  27. 27
    pep_castefa March 31st, 2011 on 09:16

    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.

  28. 28
    Almog Design March 31st, 2011 on 09:22

    @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.

  29. 30
    John July 12th, 2011 on 22:13

    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.

  30. 31
    Dan July 13th, 2011 on 05:07

    Awesome tips :) much appreciated.

  31. 32
    Dan July 13th, 2011 on 06:31

    one thing, when trying to use the clean up multiple events technique, i am getting an ‘incompatible override’ error. any ideas?

  32. 33
    kikolin August 10th, 2011 on 10:50

    About AS3 and listeners. A must read! http://t.co/wg250VS

  33. 34
    Jose Manuel Soleto August 10th, 2011 on 11:00

    About AS3 and listeners. A must read! http://t.co/wg250VS

  34. 35
    jb October 8th, 2011 on 10:33

    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);

  35. 36
    jb October 8th, 2011 on 10:35

    i meant to include “uncle” with “parent” and “great uncle” in the above explanation, incase anybody didn’t already get that.

  36. 37
    jb October 8th, 2011 on 10:40

    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”)

  37. 38
    Tiputopia October 23rd, 2011 on 22:53

    ActionScript 3 Event Listeners Tips & Tricks | Almog Design http://t.co/qi6cIyWa

  38. 39
    byron October 29th, 2011 on 00:40

    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

  39. 40
    Rhys Willis March 26th, 2012 on 15:04

    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.

Leave a Comment