Jump to content

How to Use Event Listeners with ActionScript 3.0

0
  chco's Photo
Posted Dec 11 2010 05:20 PM

The concept of event listeners is pretty simple. Essentially, you tell an object to listen for an event and react if that event occurs. The following excerpt from Learning ActionScript 3.0, Second Edition shows you how to use event listeners in ActionScript 3.0.
Imagine that you’re sitting in a busy airport. Lots of things are going on around you, all of which can be thought of as events. If you had no particular reason to be at the airport, you might ignore all of these events. They would still occur, but you would not listen for them.

However, if you’re scheduled to depart on an upcoming flight, you might establish a few listeners. For example, you might listen for a loudspeaker announcement about your flight number but ignore everything else. Or, you might also listen for a loudspeaker announcement about your destination city. You might even plan to listen for a third event: the inclusion of your airline in an announcement.

In all cases, the reaction to these events would be to pay attention to the announcement hoping to learn more about your flight. Other events might still occur in the airport, including other announcements, but without listening for those events, they would wash over you without reaction.

ActionScript 3.0 event listeners work much the same way. Creating an event listener, in its most basic form, is fairly straightforward. The first item needed is the object that will listen for the event. A button is a good example to start with. The addEventListener() method is then used to assign a listener to that object. This method requires two arguments. The first argument is an event to listen for—one that is appropriate for your goal. For example, it makes sense for a button to listen for a mouse event, but less so to listen for the end of a video or a resizing of the stage. The second argument is a function to execute when the event is heard.

Here’s an example of code that uses a button with the instance name rotate_right_btn and a function called onRotateRight(). This can be found in the simple_event_listener.fla source file.

1    rotate_right_btn.addEventListener(MouseEvent.MOUSE_UP, onRotateRight);
2    function onRotateRight(evt:MouseEvent):void {
3        box.rotation += 20;
4    }


The event this code is listening for is a mouse up event—that is, when the mouse button is released while over the button. In ActionScript 3.0 syntax, events are typically grouped together in classes, and the event itself is usually defined as a constant—a variable that cannot be changed after it’s defined. Using constants, when you know a value will never change, reduces errors because the compiler will warn you if you try to change them. Constants are usually typed in all uppercase letters, with multiple words separated by underscores.

The MouseEvent class contains constants that refer to mouse events like MOUSE_UP and MOUSE_DOWN. Other examples of events are ENTER_FRAME, found in the Event class and used to react to playhead updates, and KEY_UP, found in the KeyboardEvent class, for reacting to user keyboard input.

Note: Separating mouse events into discrete up and down events allows you to react independently to each event. That is, you can assign one listener to the down event and another to the up event. This can be useful when creating draggable objects. You can start dragging on mouse down, and then stop dragging on mouse up. You can also use a simpler mouse event called CLICK, which requires both the down and up stages of the user’s click process to trigger a listener.

The second argument in the addEventListener() method, the function that is called when the event is received, is listed by name only, without the trailing parentheses. This is because you are referring to the function, not actually calling it. The listener will do that for you when the event is received. In this example, onRotateRight refers to the onRotateRight() function, defined in lines 2 through 4.

To review the syntax, the braces define the function’s contents. In this case, line 3 adds 20 degrees to the current rotation value of the movie clip box.The void that follows the function name and parentheses indicates that no value is returned by the function.

However, new to our discussion of functions is the fact that when functions are used in event listeners, the function requires a single parameter. This parameter receives information not from any ActionScript you write, but rather from the event. In this case, we arbitrarily named the parameter evt. (You may also see e or event used in other resources, but any valid parameter name will work.)

Without a parameter in place to receive that incoming data, you will get an error that says something like, “Argument count mismatch. Expected 0, got 1.” It will also tell you which function has the problem to make it easier to find. The error means that the function expected no arguments coming in, because no parameters were defined. Instead, one argument was received, resulting in a mismatch.

You’ll get used to this quickly, and reap the benefits. The data received usually contains useful information about the event and element that triggered the event. You can parse this information for use in the function. In keeping with good error reporting, the parameter should have a data type that matches the type of data being sent into the function. In this case, the event that triggered the listener was of type MouseEvent. Using this as the parameter data type will make sure that the listener receives only a MouseEvent, or the compiler will warn you to the contrary.

Note: It is also possible to type an event listener parameter with the more generic Event class, from which other built-in ActionScript 3.0 event classes are extended. This will allow more than one type of event to call the same function.

To illustrate the use of this argument data, let’s look at another mouse event example, found in the start_stop_drag.fla source file. This time, however, we’ll use two events, and use the incoming information to identify the target of the event—speaking generically, the object at which the event occurred. Specific to this case, the target is the object that was clicked.

1    myMovieClip.addEventListener(MouseEvent.MOUSE_DOWN, onStartDrag);
2    myMovieClip.addEventListener(MouseEvent.MOUSE_UP, onStopDrag);
3    function onStartDrag(evt:MouseEvent):void {
4        evt.target.startDrag();
5    }
6    function onStopDrag(evt:MouseEvent):void {
7    stopDrag();
8    }


In this example, two event listeners are assigned to a movie clip in lines 1 and 2. One listens for a mouse down event, another listens for a mouse up event. They each invoke different functions. In the first function, the target property of the event, which is parsed from the function argument, is used to identify which object received the mouse event. This allows the onStartDrag() function in lines 3 through 5 to start dragging the movie clip that was clicked. The onStopDrag() function in lines 6 through 8 then stops all dragging when the movie clip receives a mouse up event.

The best thing about this example is that the target property identifies the movie clip without an instance name. This generic approach is very useful because it makes the function much more flexible. The function can act upon any appropriate object that is clicked and passed into its parameter. In other words, the same function could start and stop dragging any movie clip to which the same listener was added. The following additional lines, adding the same functionality to a second movie clip called myMovieClip2, demonstrate this:

9    myMovieClip2.addEventListener(MouseEvent.MOUSE_DOWN, onStartDrag);
10    myMovieClip2.addEventListener(MouseEvent.MOUSE_UP, onStopDrag);


Note: A similar event property is currentTarget, which references the object to which the event listener is attached. When a listener is attached to a single movie clip (as in the cited example), target and currentTarget are the same because you click on the object with the listener. However, events can pass from a parent clip down to any child clips within. When the listener is attached to the parent and you click on the child, target will still refer to the child, because that’s what you clicked. The currentTarget property, however, will refer to the parent movie clip because that’s the object to which the listener is attached. For more information, see “The Event Object,” an event-related post at http://www.LearningActionScript3.com.

Finally, this example’s last modification demonstrates that more than one object can also call the same listener function. It is possible, while dragging an object, to move your mouse so quickly that the mouse up event occurs outside the bounds of the object you’re dragging. If that occurs, the object would not receive the mouse up event, and the drag would not be stopped.

One way to get around this is to attach another listener to the stage, and set that listener to also call the onStopDrag() function. This way, whether your mouse up occurs over the movie clip or over the stage, the dragging will cease.

11    stage.addEventListener(MouseEvent.MOUSE_UP, onStopDrag);


Learning ActionScript 3.0

Learn more about this topic from Learning ActionScript 3.0, 2nd Edition.

If you're new to ActionScript 3.0, or want to enhance your skill set, this bestselling book is the ideal guide. Designers, developers, and programmers alike will find Learning ActionScript 3.0 invaluable for navigating ActionScript 3.0's learning curve. You'll learn the language by getting a clear look at essential topics such as logic, event handling, displaying content, classes, and much more. Updated for Flash Professional CS5, this revised and expanded edition delivers hands-on exercises and full-color code samples to help you increase your abilities as you progress through the book.

See what you'll learn


Tags:
0 Subscribe


0 Replies