Monday, November 29, 2010

How to Create an AS3 Event Listener

Part 1: Introduction to AS3 event handling
Part 2: How to create an AS3 event listener
Part 3: The AS3 event object
by Alberto Medalla
Lecturer, Ateneo de Manila University

In this next part of the Flash AS3 Event Handling tutorial series, we're going take a look at how to write event handling code.

According to the Adobe Flash ActionScript 3 documentation, there are 3 important elements that need to be identified when working with event handling in Flash. These are: (1) the event, (2) the response, and (3) the event source. We've already introduced the concepts of events and responses in the first part of this lesson, but let's go ahead and take a look at them again with a little more detail. And then after that, let's take a look at what the event source is.

An event refers to a specific occurrence that happens as your Flash movie runs. In ActionScript 3 event handling, events are identified by specifying the event class as well as the event constant.

Event classes can be thought of as the different groups used to classify different kinds of events. There's an event class, which is also called Event. Some events that fall under this class are the complete, deactivate, and open events. Another example is the keyboard event class, which is written as KeyboardEvent. Some events that fall under this class are the key down (i.e. when the user presses a keyboard key) and key up (i.e. when a key is released) events. There's also another class for mouse events, which is written as MouseEvent.

Event constants are specific names that refer to the events themselves. Let's consider the MouseEvent class, a few of the events that fall under this class are: mouse clicks and mouse roll overs (i.e. when the cursor hovers over a button). The constant for a mouse click is written as CLICK. For a mouse roll over, it is written as ROLL_OVER.

Once these elements have been identified, writing the event in code takes on this form:

So for example, if you were to specify a mouse click event then you would write: MouseEvent.CLICK. And if you were to specify a mouse roll over event, then you would write: MouseEvent.ROLL_OVER.

A response refers to what is going to happen once Flash detects the occurrence of an event. For example, after a button is clicked (MouseEvent.CLICK), we can instruct the Flash movie to respond by playing an audio file. The response is specified as a function. This function's body will contain the line(s) of code that will tell Flash what to do. This function, referred to as an event listener (also sometimes referred to as an event listener function or listener function), will be called immediately after the specified event is dispatched and detected.
function eventListener()
     // response to make when the event happens
REMINDER: The terms event listener, event listener function and listener function all refer to the same thing - it is a function that is registered to execute when a specific event occurs.

An event source refers to the object that is directly related to the event. In most cases, it is the object from which the event originates from. For example, when dealing with mouse click events, the button that was clicked would be the object that the mouse click happens to, and is therefore considered as the event source. Another example would be when a URLLoader object loads an external text file. For instance, when a URLLoader finishes loading the file, this is considered as an event as well. In this case, the URLLoader is the one responsible for loading the external text file and is therefore considered as the event source. This event source can also be alternatively referred to as the event target.

After identifying these 3 elements, you bring them all together using the addEventListener() method. The addEventListener() method registers the event listener function with the event source so that the event listener function can "hear" when the event is announced. This is essentially what connects the event listener function to the event. Once an event listener function is registered with an event source, you can think of it as the event listener function sitting there quietly, just waiting to be told or "listening" for when the event is dispatched or announced. Once the event is announced, the event listener function will then run, enabling the Flash movie to make the appropriate response.

The syntax for writing event handling code would be:
eventSource.addEventListener(EventClass.EVENT_CONSTANT, eventListenerFunctionName);

function eventListenerFunctionName(e:EventClass):void 
     // code for response goes here

Let's create an example:
  1. Create a new Flash ActionScript 3.0 document
  2. Draw a shape on the stage and convert it into a Button symbol
  3. Give this instance an instance name of my_btn
  4. Create a new layer for the ActionScript, then select frame one of this layer
  5. Go to the Actions Panel and type the following code in the Script pane:
    my_btn.addEventListener(MouseEvent.CLICK, onClick);
    function onClick(e:MouseEvent):void
         trace("The event handler works!");
You've just written some code that handles a mouse click event. Go ahead and test your movie. When you click on the button, you should see the phrase The event handler works! come out in the output window.

We've learned that there are 3 important elements when it comes to working with event handling in Flash AS3 (the event, the response, and the event source). But when it comes to writing the event handling code, the code itself is made up of 2 parts: (1) the add event listener statement, and (2) the event listener function.

Whenever an ActionScript 3 event happens, the event gets dispatched or announced within the Flash player. Once the event is announced, the event listener function that is registered with the event's source will execute. To register an event listener function with an event source, the addEventListener() method is used. Registering the event listener function with the event source will enable the event listener function to know when to respond.

In order for the event listener function to respond at the right time, the add event listener statement must contain the following 3 pieces of information:
  1. the event source
  2. the event
  3. the name of the event listener function to be executed once the event is triggered
In the example we created, the add event listener statement would be:
my_btn.addEventListener(MouseEvent.CLICK, onClick);
Event Source: my_btn
Event: MouseEvent.CLICK
Event Listener Function Name: onClick

This is the function that gets executed in response to the event. The event listener function's body will contain the lines of code that will make up whatever response we'd like the Flash movie to make whenever the event is dispatched (e.g. playing a sound when a button is clicked, displaying an image when you roll over a button, etc...). In the example that we created, the event listener function would be:
function onClick(e:MouseEvent):void
     trace("The event handler works!");
The event listener knows that it is the function that needs to be executed because its name matches the event listener function name that was specified in the add event listener statement.

NOTE: You will also notice that the event listener function has a single parameter - e. We'll talk about that later.

At this point, let's take a look at a summary of the event and response process that took place in our code example:
  1. User clicks on the my_btn button

  2. The event (my_btn being clicked) is immediately dispatched

  3. The event listener function "hears" the event being dispatched

  4. The event listener function runs

So that is the basic flow of how events in AS3 are handled: (1) the event occurs, (2) it gets dispatched, (3) the event listener "hears" the event being dispatched, (4) and the event listener function runs.

Now let's go back to the event listener function and lets talk about the single parameter that it is set to accept. In our example, the parameter is named e and is of the MouseEvent data type.
function onClick(e:MouseEvent):void
     trace("The event handler works!");

Every time a dispatched event triggers an event listener function to run, information gets passed to that event listener function. This information is contained in what is referred to as an event object. This parameter is what is used to accept that event object whenever it gets passed to the event listener function. Some of the information contained in this event object include: the event source and the event that occurred.

All event listener functions must always have a parameter for the event object regardless of whether or not the parameter will be used anywhere in the function body. In our example, we do not make use of the event object parameter, but if we removed that parameter, our event handler code will NOT work.

When creating the event object parameter, its data type is set to match the event class of the event that is being watched out for. In our example, the event listener is watching out for a mouse click, which is under the MouseEvent class. So the data type for the parameter should be MouseEvent as well:
myObject.addEventListener(MouseEvent.CLICK, myListenerFunction);

function myListenerFunction(e:MouseEvent):void
     // function body

If we were watching out for a KeyboardEvent, then the parameter should have the KeyboardEvent data type instead:
myObject.addEventListener(KeyboardEvent.KEY_DOWN, myListenerFunction);

function myListenerFunction(e:KeyboardEvent):void
     // function body

In the examples, the parameter name used is e. It's NOT a requirement that you use the name e, since parameter names are author defined. The usage of e is more of a common convention, and is what will be used throughout this tutorial series.

In the next part of this series on Flash AS3 event handling, we are going to take a closer look at the AS3 event object.

PREV: Introduction to Flash AS3 Event Handling
NEXT: The AS3 Event Object


  1. Really nicely done! I have been reading and watching tutorials on Actionscript 3.0 and this is very informative. Thank You!

  2. You're welcome! Glad you like it! :)

  3. Well structured and written - really enjoyed learning AS3. Your tutorials are engaging, relevant and useful. Many thanks.

  4. Thank you for the kind words! :)

  5. Awesome tutorials...Very clear....even an end user can code after reading ur descriptuve notes..Thankyou very much for giving us a huge support of learnig..keep going...

  6. Very nice tutorials for begiers like me to start with...each and every aspect is explained in detail and simple language..

  7. After MONTHS of GOOGLING and trying out the thousands of links for AS3 HELP, I stumbled across this site...

    All I can say is FANTASTIC! Within 1 hour I had understood the events, listening and functions CLEARLY!

    It took me back to the days of Adobe Photoshop and the 'Photoshop Bible' book. Written in a language that 'normal' people understand.

    Thank you VERY much.

    1. Me too! First time I find something so valuable, thanks a million!

  8. i was gonna say the same .. this is valuable .. u should be on google ranking #1.

    btw .. i've a quick noob question - the following code doesnt work in my adobe flash

    my_btn.addEventListener(MouseEvent.CLICK, onClick);

    function onClick(e:MouseEvent):void
    trace("The event handler works!");

    the words - FUNCTION and VOID appear in some other color (not blue) .. which m guessing as the reason for all my errors

    can u please tell me how do i fix that ??

  9. This is super Helpful ! Thank you so much for taking the time to make all this :)

  10. This is very helpful for me.Thank so much..........:)

  11. Nice Explanation...