Apr 29 2008

Tutorial: Event Listeners in Flash AS3 explained

Published by admin at 11:35 pm under Basics, Flash AS3

Why should I care about Event Listeners?

If your ambitions in Flash AS3 extend beyond that of basic animation you will NEED to care about Event Listeners because the flow of your entire project will depend on them. They are the ignition to your movies. They allow you to respond to input from users (whether it be the mouse or the keyboard or any other form) and take action with that input. In short, Event Listeners are part of the life-blood of Flash programming.

What is an Event Listener?

Very simply, an event listener is a way to execute a function when a designated event takes place. Most importantly, an event listener is a way for Flash trigger certain actions (or alert the programmer) when a certain event has happened and then pass key information to that function.

Think about it like this. If a person clicks on a button, there are a couple of ways to logistically determine if the button was clicked. One option would be to run a timer that fired every millisecond to check if the mouse button was down. Technically this would work, but it would become very cumbersome for the programmer to keep track of so many timers. Many of the other options are equally as cumbersome and unhelpful. The preferred solution is to use an Event Listener.

Understanding the AS3 Event Listener Model

The event model is crucial to the flow of complex Flash applications. While you may not have a need for it if you only designing animations (in which case gotoAndPlay() and stop() will be your AS3 favorites) in any other application you will want to harness the power of events. They are crucial for doing things like determining when a user has clicked a button, or figuring out when a remote image has completed loading.

The model itself is part of AS3’s implementation of an Object Oriented Programming (OOP) style. Don’t be overwhelmed by its name, however, its really just a way of thinking about the world and modeling it inside your code. Think of it like this: everything in the world is an object. Some things are a combination of multiple objects that work together to create an even more complex object. And yet, each object by itself is a combination of THREE essentially things: its properties (states of being, characteristics, features, etc), its methods (the actions and functions it can perform), and its events (the things that happen to it, its circumstances). Events, then, are really only one third of the picture, but a very important third.

Continuing with this OOP idea, the event is only going to fire when something happens to it. However, in flash it is a two part system. Part One is telling Flash what event it should be on the look-out for. How should Flash know it needs to send an alert when a button is clicked if you never tell it? This is achieved using the addEventListener function. The Second Part is the actual firing function. This is the code that gets executed when the event happens. These functions are just like any other, except they take as their first parameter an object that contains VERY helpful information. More on that later.

Understanding Part One of the AS3 Event Listener Implementation

If you are joining us from Flash 8’s AS2 model then the newer AS3 Event Listener based language may give you some difficulty. I hope that you are familiar with the idea of an event listener, but it is actually implementation in AS3 will be slightly different. In the old model, we assigned the actual function, code and all, like in the example below:

var focusListener:Object  = new Object();
focusListener.onSetFocus = function(oldFocus:TextField, newFocus:TextField) {
oldFocus.border = false;
newFocus.border = true;
}

In AS3, rather than assigned the entire function, we simply reference the function name within the addEventListener function, like below:

var focusListener:MovieClip  = new MovieClip();
focusListener.addEventListener(MouseEvent.MOUSE_CLICK, handleClick);

Here we have create a new movie clip and assigned an event listener to it that will fire in the case of it being clicked on by the mouse. (Note: contrary to the example above, the Object class in AS3 does not have event dispatching capability. Instead, use the Sprite class or a derivative of the Sprite class, such as the MovieClip class).

In every case of assigning an event listener, you will want to start with the instance name. You can remember this because this is the name of the object to which you want the event to happen. For instance, it is the name of the button that you are assuming the user will click.

This is followed every time by the dot operator (“.”) and then the function name addEventListener. This tells Flash exactly what the name implies, that it should add an event listener to the object you have specified. Of course, the next question is “what kind of listener?” and of course, “what should I do once the event has occurred?”

The answer to the first question will depend on your project. The two most frequent types of events are the general Events and the MouseEvents. To access these types, you simply type the name of the event class, for instance MouseEvent, followed by the dot operator (“.”), and then the specific type of event you’d like to listen for. Don’t worry, a mini-pop-up will appear to help you select your event type. Some MouseEvent types include: MOUSE_UP, MOUSE_DOWN, MOUSE_CLICK, MOUSE_OVER, etc. Just chose your type, hit enter, and then on to the next question.

Now we must tell Flash what to do when the event has occurred. The only real answer is for Flash to execute a function, so the next item we tell Flash is the name of the function we want it to execute. (Note: you do not need to type any quotation marks to signify a string, just simply type the function name and Flash will understand). Once you have done this, part one of the event listener model is completed.

Understanding Part Two of the AS3 Event Listener Implementation

The second part of the Event Listener model is the actual function that the Event Listener will execute. This function is THE EXACT SAME as any other function you will make in flash with only one major exception – the first parameter of the function is an Event Object. This object is the home of many important pieces of information, most notably target and currentTarget. First, let me give you some example code:

function handleClick(evt:MouseEvent):void {
trace("You clicked the "+evt.currentTarget+" button");
}

Notice how the syntax is the same. The one object that has been passed to the function I’ve called “evt” and is a MouseEvent.This object contains different properties that we’d like access to. The one I’ve used in this example is called currentTarget and it is a literal reference to the object that has been clicked, that is, our MovieClip. Thus, anything you do to currentTarget is the same as if you had done it to our MovieClip called “focusListener”. This is very powerful because now you can write just one function and instead of referring to the “focusListener” you can reference currentTarget and it can be ANY MovieClip you’ve passed. You’ve now made reusable code. And reusable code is the best code.

Other properties passed via the MouseEvent include localX, localY, shiftKey, stageX, stagey, etc. As the names imply, these are the coordinates of the mouse upon clicking (both local within the “focusListener” MovieClip and global to the stage). Each property is explained in detail in Adobe’s LiveDocs.

The trick to implementing event listeners successfully is to learn to use the currentTarget property really well so that you can program powerful functions that leverage the reusability offered by this event model. Do not expect to be a master of this all in one sitting. It takes some practice to get use to the idea of events. With effort and some help from the community you will be a pro in no time.

If you’d like to see an example of these event listeners in action you can read the article Write your first class ever… with event dispatching. Please do not hesitate to leave any comments or questions you might have on the feedback below.

Popularity: 100% [?]

8 responses so far

8 Responses to “Tutorial: Event Listeners in Flash AS3 explained”

  1. jron 12 May 2008 at 12:13 pm

    THANK YOU!

  2. adminon 12 May 2008 at 12:15 pm

    my pleasure :)

  3. Bananon 22 Jun 2008 at 1:22 am

    Hello,
    Im new to flash and I found your article very useful in understading the Event listeners more. I was wondering though, can you link an event listener to the loader component ?

    Like if a person clicks ( on mouse click) I’d want it to go to the Loader component I have on stage. Can I do that?

  4. gon 18 Jul 2008 at 8:17 am

    great stuff!

  5. Aspiring "AS" Coderon 23 Jul 2008 at 11:27 am

    This is a great post and extremely helpful, thanks so much! :)

  6. Rick Don 07 Aug 2008 at 9:49 am

    Well done, provided immediate help…thanks!

  7. [...] tutorial by Kyle Brekke [...]

  8. [...] Resource [...]

Trackback URI |