How to Create an AS3 Event Listener
Tutorials

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.

EVENT
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:
EventClass.EVENT_CONSTANT

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.

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

EVENT SOURCE
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.


FLASH ACTIONSCRIPT 3 EVENT HANDLING SYNTAX
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.

FLASH ACTIONSCRIPT 3 EVENT HANDLING CODE EXPLAINED
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.

ADD EVENT LISTENER STATEMENT
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

THE EVENT LISTENER FUNCTION
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




- As3 Dragging And Dropping Tutorial - As3 Startdrag() And As3 Stopdrag()
Exercise File: as3-drag-and-drop.fla - Flash CS4/CS5 as3-drag-and-drop.fla - Flash CS3 In this tutorial, we're going to learn how to create simple AS3 drag and drop functionality using the AS3 startDrag() and AS3 stopDrag() methods. The exercise file...

- As3: Enabling The User To Submit The Contents Inside An Input Text Field
In this lesson, we're going to learn how to add some ActionScript 3 functionality that will let a user submit the contents of an input text field by clicking on a button or pressing a keyboard key. We'll create a simple example of a Flash movie...

- Introduction To As3 Event Handling - Learn All About As3 Event Listeners
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 series of articles, we're going to learn all about the basics of Flash...

- Preloading In Actionscript 3.0 Part 2
Exercise Files: Preloader02_Start.fla bird.jpg candles.jpg We've learned about the basics of preloading in Part 1 of Preloading in ActionScript. In this lesson, we'll apply the same concepts to make a picture gallery that has the ability to preload...

- How To Pass Additional Parameters To As3 Event Handler Functions
I've recently made the leap to AS3, and one of the very first questions I wondered about was how I could pass extra arguments to event listener functions. From what I understand, event listener functions in AS3 can only have one parameter, which is...



Tutorials








.