How Listeners work in actionscript

November 28th, 2006 . by polyGeek

I would have to say that getting my head around how listeners work in Actionscript might have been the toughest aspect of AS for me. But, once you get used to it, just like everything else, it’s simple to use.

To create a listener you need three things:
1-you create an object - new object().
2-you tell that object what to do when an event happens - event handler.
3-you get the object to listen for the event - addListener.

Here’s a real world analogy: suppose you want to make a phone ring when someone calls you.

First, (#1) create a phone.

var myPhone:Object = new Object();

Next, (#2) tell it what to do when a phone call comes in

myPhone.onCallRecieved = function():Void {
makeTheRingSound();
}

And finally, (#3) tell it to listen for an incoming phone calls.

phoneNetwork.addListener(myPhone);

This last part, (3) might be the most confusing aspect so I’ll go into it with a little more detail.

Think of it this way: there’s a phone network out there that everyone is connected to. If someone uses their phone to dial your phone number then your phone will ring. Obviously you have to have a phone, the object (#1) and your phone must know what to do when it receives a phone call (#2). But there’s a little more to it isn’t there. You can’t just buy a phone and turn it on. First, to get it to work you have to register it with the network and tell it what your phone number is. That way when someone dials your number the network can determine who is listening - your phone - and send you the message.

If you hadn’t done this last step then when someone dialed your number the network would still get the event but it wouldn’t know who to tell. Once you register with the network then it will know to broadcast an event to you when your number is dialed.

So once again, you have the object - phone - the thing in your phone that acts when it receives an onCallReceived event and finally you tell the network to let you know when someone dials your number.

General form of a listener:



Here is a very simple example of a listener in Actionscript. Use the arrow keys on your keyboard to move the ball up/down, left/right. The longer you hold down a key the faster/slower it will move. So holding down on the right-arrow for a few seconds will make it move right and then holding down the left-arrow for a few seconds will slow it back down. At any time you can hit the spacebar to stop the ball and return it to the center. (Note: you must click on the SWF - black square - to give it focus so that it receives the keyboard input.)

Here’s the code that makes this all work (download zip)


Here is what’s happening above. An object is created - listener. And that object is told what to do if it gets an event called onKeyDown. And finally we tell the Key class to notify our listener when the onKeyDown event happens.

Suppose you had a Flash movie that doesn’t have any of this code. What happens when we press a key then? Well, the Flash player knows that a key was pressed and it - the Key class - looks to see if any objects need to be notified. If there are no listeners then obviously it doesn’t send any notifications.

The onKeyUp is the other event that the Key class can notify an object about. Since our listener is receiving all the events that pertain to the Key class then it gets those notifications as well. However, we don’t have any code that tells our listener what to do about it so nothing happens.

You might ask yourself, “why don’t mouse events work the same way?” That’s because the Flash developers thought that it would be so common to have mouse events associated with MovieClips and buttons that they made it simple to use. Basically, things like MovieClips automatically listen for mouse events so all you need to do is supply the code for what you want to happen, as such:

myClip.onRelease = function():Void {
// do things when someone clicks and
// releases the mouse on this MovieClip
}

That’s the #2 part of our example above. Steps #1 and #3 are done for us to make our life/coding simpler.

There are all sorts of other classes that broadcast events that you might want to listen for. If you’re using the movieClipLoader class you might want to know when something has completed loading, or with a video that is streaming into your movie you might want to know when it has completed playing. You can also use a listener to tell when the stage has changed size, or when a webcam has changed it’s status. The list goes on and on. In fact, that’s what you want to look for in the Flash help files - on. Pick a class in the Actionscript Classes folder and look for methods that begin with on. Those are the events that it broadcasts so that you can write code to manage what happens when the event is triggered.

Share and Enjoy: These icons link to social bookmarking sites where readers can share and discover new web pages.
  • del.icio.us
  • Reddit
  • Slashdot
  • StumbleUpon
  • Technorati
  • Digg
  • Facebook

8 Responses to “How Listeners work in actionscript”

  1. comment number 1 by: collis

    Fantastic tutorial Dan! Really really well written, and as always thanks so much for offering it for publication on FlashDen, i’m porting it over now!

  2. comment number 2 by: polyGeek

    Always a pleasure helping the community out.

  3. comment number 3 by: seth

    So, this movie behaves differently for me if I am running it on Firefox/PC vs Firefox/Mac, same flash player version 9.0.28 on both machines.

    The difference is that the PC version continues to fire the keyDown events, while the Mac version on register the event for each single press.

    1) Do you know why this difference exists?
    2) And more importantly, do you know how I can get the PC version to act like the Mac version, and only have it recognize the individual key presses?

  4. comment number 4 by: polyGeek

    Seth, try this:

    var keyListener:Object = new Object();

    var isKeyDown:Boolean = false;

    keyListener.onKeyDown = function():Void  {
        if(!isKeyDown) {
            trace(”keyGode: “+Key.getCode());
        }
        isKeyDown = true;
    };

    keyListener.onKeyUp = function():Void {
        trace(”keyUP”);
        isKeyDown = false;
    }

    Key.addListener(keyListener);
    I took out a bunch of code in the onKeyDown method just to shorten this up.

    All I did was add a boolean to track if the key is in the down state. If it is then don’t do the onKeyDown stuff. However, the isKeyDown is set at the end of the method so it will run once when the key is pressed. Afterwards the code in the if/statement will be skipped until the key is released and pressed again.

    Let me know if you have any questions.

  5. comment number 5 by: seth

    Awesome. thanks!

    Also, Firefox/PC with wmode set (ref: http://tinyurl.com/y8brne - see the comments) doesn’t fire Key.isDown(). I suppose I could rely on the boolean you introduced in the previous comment.

    So, instead of
    if(Key.isDown(Key.CONTROL))

    I could do

    if(isKeyDown && Key.getCode() == 17)

  6. comment number 6 by: polyGeek

    @Seth, I’m glad that helped.

    From reading the comments on FlashDocs it seems that the problem revolves around the SWF getting focus from the browser. There probably isn’t anything that can be done inside of Flash to fix this. Perhaps someone out there will write some Javascript that will browser detect and do what’s necessary to give the SWF focus under all conditions.

  7. comment number 7 by: Vladimir

    Awesome. But…is it possible to add some further browser events listener?
    I need listener which will listen if user hit the BACK (and forward) button on browser, and do something in flash when this happens.

  8. comment number 8 by: polyGeek

    A swf won’t pick up events like clicking the back/forward buttons in a browser. For instance, if the swf on a page doesn’t have focus then it won’t pick up keyboard events.

    However, the browser will of course get these events. What you would need to do is write Javascript to listen for these events and then pass that info on to Flash. I would use the ExternalInterface for that. If you look around you should be able to find someone who’s written most of the JS code that you’ll need. The key will be intercepting the back/forward buttons so that they don’t actually take the user to a different page.
    Adobe has a great tutorial on Flash/Javascript communications. Here’s a link to the specific info on the ExternalInterface.

Leave a Reply

Name

Mail (never published)

Website

- Why ask? This confirms you are a human user!

   




© Copyright 2008 polyGeek.com / Dan Florio, All Rights Reserved Except Where Explicitly Stated
Web Developement Blogs - Blog Catalog Blog Directory
M2 Websites