As just stated, a listener is an object that listens for events. You can specify your class as a listener for
a particular event by calling a function named addEventListener. You pass in the name of the event
you want to listen for and the name of a function in your class that will be the handler. Here’s an
example:
addEventListener("enterFrame", onEnterFrame);
Additional optional parameters can be used when adding event listeners, but we won’t do so in this
book; the preceding syntax is all you’ll need for most applications of events.
Notice that the event name, "enterFrame", is a string. This is what is known, with a bit of contempt,
as a magic string. Why magic? Because if you accidentally mistype it as, say, "entorFrame", the compiler
will magically accept it without a complaint, even though there is no such event name, after
which you will see hours of your time magically disappear while you try to figure out why your event
handler is not being called.
But AS 3 has even this handled. Instead of using magic strings such as "enterFrame", you can use
properties of the Event class instead. For example, in the preceding case, you would write the following:
addEventListener(Event.ENTER_FRAME, onEnterFrame);
If you went and looked at the value of Event.ENTER_FRAME, you would find that it is simply the string
"enterFrame". Now, you might be thinking that it is just as easy to mistype the property as
Event.ENTOR_FRAME. But the improvement here is that if you do, your program will refuse to compile
and will tell you right away that there is no such property on the Event class. It will point you not only
to the exact line where you made this error, but also to the exact character in that line where it first
encountered a problem. It can’t get much better than that, unless the compiler starts correcting your
mistakes and writing code for you.
In addition to the event types on the Event class, there are other event types set up in the same way
on other classes, such as MouseEvent.MOUSE_DOWN, KeyboardEvent.KEY_DOWN, TimerEvent.TIMER, and
so on. While these all stand for simple strings, such as "mouseDown", "keyDown", and "timer", it is best
if you just forget about the strings altogether and use the properties only.
The next important thing to know is that sometimes, such as in the previous example, you can call the
addEventListener function directly in a class. In this case, you are actually telling the class to listen for
its own enterFrame event. In some cases, though, you want to listen for an event generated by
another object. An example is if you have a sprite named mySpriteButton that is acting as a button.
When the user clicks that sprite, it will generate a mouseDown event. To listen for the mouseDown event
coming from that sprite, you call the addEventListener method of that sprite, like so:
mySpriteButton.addEventListener(MouseEvent.MOUSE_DOWN, onSpritePress);
The final thing to take note of is that unlike earlier versions of ActionScript, which had to have specifically
named event handler functions such as onEnterFrame, in AS 3 you can name your handler functions
whatever you want when you add listeners. In the enterFrame example, I used onEnterFrame as
a handler, but only because it’s a fitting name and one I’ve gotten used to. In AS 3, onEnterFrame has
no inherent meaning at all. I could have just as easily named my enterFrame handler move, run, or
doSomethingCool. By convention, however, event handlers often start with on, followed by something
that describes the event and perhaps where it came from, such as onStartButtonClick,
onConfigXMLLoad, or even onRocketCrash. Alternatively, some people like to add the Handler suffix to
the event name to create the handler’s name—for example, enterFrameHandler. Again, it’s a matter
of preference. The most important thing is to be consistent, so that you know an event handler is an
event handler just by looking at it.
Now, I’ve been saying that a listener listens for events, but perhaps a more accurate description is that
the listener is notified of events. Internally, the object that is generating events keeps a list of every
object that has added itself as a listener. If an object is capable of generating different types of events,
such as mouseDown, mouseUp, and mouseMove, it will keep a list of listeners for each event type it can
generate. Whenever one of these events occurs, the object runs through the corresponding list and
lets each object in that list know what event has occurred.
Yet another way of describing events is to say that the object that becomes a listener is subscribing to
a particular event. And the object that generates the event is broadcasting the event to all its subscribers.
Additionally, if you no longer want an object to listen to events, you can tell it to stop listening, or
unsubscribe, by calling the removeEventListener method:
removeEventListener(Event.ENTER_FRAME, onEnterFrame);
This tells the object to remove the listener from its list of listeners for that particular event, so it will
not receive further notifications.
Let’s go ahead and see some of this in action. The following code creates a new sprite, puts it on stage,
draws some graphics in it, and adds an event listener to it. Start out with the skeleton application presented
earlier, and add the code to that:
package {
import flash.display.Sprite;
import flash.events.MouseEvent;
public class EventDemo extends Sprite {
private var eventSprite:Sprite;
public function EventDemo() {
init();
}
private function init():void {
eventSprite = new Sprite();
addChild(eventSprite);
eventSprite.graphics.beginFill(0xff0000);
eventSprite.graphics.drawCircle(0, 0, 100);
eventSprite.graphics.endFill();
eventSprite.x = stage.stageWidth / 2;
eventSprite.y = stage.stageHeight / 2;
eventSprite.addEventListener(MouseEvent.MOUSE_DOWN,
onMouseDown);
eventSprite.addEventListener(MouseEvent.MOUSE_UP,
onMouseUp);
}
private function onMouseDown(event:MouseEvent):void {
trace("mouse down");
}
private function onMouseUp(event:MouseEvent):void {
trace("mouse up");
}
}
}
What is going on here? Most of the init function is simply there to create a sprite, draw a circle in it,
and center it on the stage. It’s the final two lines that are important. Here the class adds itself as a listener
for two events, MOUSE_DOWN and MOUSE_UP. Note that these are properties of the MouseEvent
class, and that class must be imported. As handlers, you pass in the functions onMouseDown and
onMouseUp, which are defined right after that. Handlers generally get passed an event object that contains
some information about the event. Minimally, it would contain information about what object
triggered the event. In the case of mouse events, it contains information about the mouse location at
the time of the event, which mouse button was pressed (if any), and so forth. For keyboard events, it
would contain information about which keys were pressed at the time of the event; the state of other
keys, such as the Ctrl, Alt, and Shift keys. Consult the help files to see what information is included
with what types of events.
Save the preceding example as EventDemo.as and compile it using the method of your choice, as
described earlier. When you run the SWF itself, you’ll see that it traces a message each time the mouse
is pressed or released on the new sprite. If you are using Flex Builder 2, don’t forget to debug—not
run—your application, and if you are using the free SDK, use the correct method for whatever solution
you are using to trace. Make sure you get this sample working. It’s a pretty simple example, but
it’s a good test to ensure your development environment is set up correctly.
If you are new to ActionScript, and you get this working and actually understand it, congratulations!
You have just moved from “beginner” up to “intermediate” status.
OK, now that you know a little bit more about handlers, you can get a better understanding of listeners.
Earlier, I said that an object that generates an event broadcasts that event, or notifies its listeners of
the event. How does it do that exactly? Well, all it really does is call the function on that object that
has the correct handler name. In the previous example, the class EventDemo added itself as a listener
to a couple of the sprite’s events. Internally, the sprite keeps a list for each event. So it has a list for the
mouseDown event, and another list for the mouseUp event. These are probably just simple arrays. Each
list now contains a reference to the main movie, which is an instance of the EventDemo class.
When the user presses the mouse button on the sprite, the sprite responds, “Whoa! Mouse down!
Must notify listeners!” (or something like that). It then goes through its mouseDown list and sees what’s
in there. The sprite finds a reference to the main movie and a reference to the function that was specified
as a handler, which in the example is a function named onMouseDown. It then simply calls that
function on that listener. If other objects had registered as listeners to the mouseDown event, they
would be on the list, too, and whatever handlers they had defined would also be called.
The same thing happens when the mouse is released, except it looks at its mouseUp list.
One important technical note on handlers in AS 3 is that most scope issues are totally handled. This
issue is a bit complex, but an easy way to understand it has to do with where the handler function
thinks it is when it is called. Although the AS 2 event architecture seems similar to that of AS 3 on the
surface, a class method being called as an event handler in AS 2 is executed as if it were a method of
the calling object, not the class in which it is defined. If this sounds confusing, that’s because it really
was, and there was a whole other class—the Delegate class—that was created just to try and handle
this issue. And if this paragraph makes no sense to you at all, relax and be thankful that it is something
you generally won’t have to think about in AS 3!
Those are the basics of events and handlers through the ages.