Events 101

For this week’s training, we’re going to discuss Events in ActionScript. This will be a two-part training, with part one focusing on the basics of events, and how to use them, with part two covering more advanced uses of events.ActionScript is an event-driven language. Once a SWF file has been opened and the initial constructor code has run, pretty much all other code in the file is driven by events. As a result, ActionScript developers need to have a solid understanding of what events are, how they work, and how to use them.

What’s an Event?

So, what is an event? “An event is a noteworthy runtime occurrence that has the potential to trigger a response in the program.” (Essential ActionScript 3.0, p. 202, Moock) Pretty much anything that happens in an ActionScript application is driven by events.

Types of Events

There are two types of events in ActionScript 3.0: built-in and custom events.

Built-In Events

Built-in events are events that are created and dispatched by the Flash Player. Things like mouse clicks, keyboard presses, when loading an image completes, etc.

Custom Events

Custom events are events created and dispatched by objects that your code manages. This could be when parsing an XML file is complete, or a character in a game dies. Pretty much whatever you determine to be a noteworthy event in your code can be dispatched.

The Basics

When those “noteworthy runtime occurrences” occur, an Event object is created by an event dispatcher. An event dispatcher is an object which creates and dispatches an event, essentially broadcasting the fact that something specific occurred. The event dispatcher could be the Flash Player for built-in events, or a custom class that extends the EventDispatcher class.Any objects that care about when that event happens will then receive an Event object notifying them of the occurrence of the event. These objects will then create a function to handle the event, which will do something based on that event having happened.In short, there are three main components to Events:

  • Event Dispatchers
  • Event Objects
  • Event Handlers

Working with Events

The basic process of working with events is as follows:

  1. Determine the name of the event you care about.
  2. Determine what the type of the event is.
  3. Register to listen for the event.
  4. Create an Event Handler.
  5. Wait for the event to occur.

Determine the Event Name

The first step in working with an event is to decide what type of event you care about. Each event that is dispatched has a name associated with it. The names are descriptive of the event that occurred. These event names are Strings like “click”, “complete”, and “mouseOver”. To determine the names of events that are dispatched by a particular object, check the documentation for the object. There you’ll find a list of the different events dispatched by the object, and under what conditions they are dispatched.While event names are Strings, and can be used as above, the Event class defines these names as constants such as Event.COMPLETE or Event.CANCEL. One of the benefits of using these constants vs. the String names is compile-time checking for your event handlers. If you register for events using the event name as a string, the compiler can’t tell you that you registered for a “compete” event, when you meant to listen for “complete” events. Another is the code completion you get when writing your code.

Determine the Event Type

All events are an object of the type Event, or a subclass of Event. These Event objects are created by the event dispatcher, and passed as a parameter to the event handler function. In most cases, the base Event class is used. However, there are times where an event will need to carry some additional information with it when it is dispatched. This information is often data about what exactly happened when the event was dispatched. For example, when a user clicks on something, a MouseEvent is dispatched.The MouseEvent object contains properties that would be useful to something that cares about when an event related to a mouse happens. Mouse events include MouseEvent.CLICK, MouseEvent.ROLL_OVER, and MouseEvent.DOUBLE_CLICK, among others. In addition to describing the type of event that was triggered by the mouse, MouseEvent can also tell you if there were any keyboard buttons being pressed at the time of the MouseEvent, or what position the mouse cursor was at when the event occurred.

Register to Listen for the Event

Once you have determined what event you want to listen for, and the type of event that will be dispatched, you’ll need to register with the event dispatcher to listen for that event. This tells the event dispatcher that you care about when that event happens.To register for the event, you’ll use the EventDispatcher.addEventListener() method:

EventDispatcher.addEventListener(eventName, eventHandler);

To properly use this, EventDispatcher will be a class that extends EventDispatcher, eventName will be the name of the event you want to handle, and eventHandler is the code that will run when the event is dispatched. For example, to listen for when a button is clicked:

myButton.addEventListener(MouseEvent.CLICK, onButtonClick);

In the example above, when myButton is clicked, a MouseEvent object will be created, and dispatched to any event handlers registered to listen for that event.

Create an Event Handler

An Event Handler is a function you define that will handle the event. When the event dispatcher dispatches the event, the event handler function will be called, and the instance of Event created by the dispatcher will be passed to the event handler function as a parameter. Therefore, your event handler function will need to receive at least one parameter, of the type of event being dispatched. To continue the example above, the event handler might look something like this:Picture 3.pngEach time that myButton is clicked, the onButtonClick() method will be called, and will receive a MouseEvent as it’s parameter.

Wait for the Event to Occur

So, now that we’ve figured out the event name and type, registered to listen for it, and created a function to handle the event, now what? Now we wait. There’s really not much else to do now, other than wait for that event to happen, so that our code can run.

Event Objects

Now that we’re listening for events, and handling them, what’s in this Event object that’s being thrown around? The Event object contains properties that describe the event. Event.type is the type of event that was dispatched. In the case of a MouseEvent, this could be a click, roll over, or when the mouse moved. The target property will tell you what object initially dispatched the event. The eventPhase states where the event is at in the event flow. (The event flow will be covered in part two of the training.)These properties can be very useful in helping you minimize the amount of code you need to write. For example, suppose that we’re building a game, where the player’s actions are based on clicking one of four buttons on the screen. Initially, we might consider creating four event handlers, one for each button.Picture 4.pngThese all do pretty much the same thing, but slightly differently. If you look closely, we’re duplicating a lot of code, and wasting time. Plus, if choose to add another button for another action, we’ll need to write another event handler. This is a simple example, but you should be able to see how things could spiral out of control fairly quickly.A better alternative would be to register one event handler function with each button, and based on the event’s target property, move the player based on which button was pressed.Picture 5.pngNow, instead of four event handlers, we only have one, that uses Event.target to determine which action to take. You could do the same thing by using Event.type, and perform similar actions based on the type of event. Have the player move if you simply click a button, but have them move a little bit faster if the button is double-clicked.Picture 6.pngThe choice is yours – you can simply listen for the event to happen, and do something. But by inspecting the event and using the info provided, you can often save time and have smarter event handling.

Dispatching Events

You should now understand the basics of how to register for an event, and how to handle it. Handling the built-in events dispatched by the Flash Player can get you though most of the tasks you’ll encounter when writing your code. However, what if you’ve written a custom class, and other classes need to know when something happens to an instance of that class?Dispatching events from your own classes is as simple as having your class extend EventDispatcher. You can either extend the class directly, or extend a class that already does. For example, if you extend Sprite, your class will also extend EventDispatcher. If for some reason your custom class cannot extend EventDispatcher, you’ll then need to implement the IEventDispatcher interface. This article will cover extending EventDispatcher.Suppose that you’re writing an application to display the current temperature. For the time being, we won’t worry about wiring up a thermometer to a Flash application, we’ll just assume that it’s happened and it works wonderfully. We’re going to create a custom Thermometer object that will dispatch an event whenever the temperature changes. When the event handler receives this event, it will then ask the Thermometer instance for the new temperature.To do this, we’ll create a new Thermometer class that extends EventDispatcher. Every time the temperature changes, we’ll dispatch an event of the type Event.CHANGE. For this example, we’ll just have a timer that fires an event at a regular interval, and updates the temperature to a random value.Picture 8.pngIn our application, we’ll create a new instance of this Thermometer class, and register to listen to it’s Event.CHANGE event.Picture 9.pngCongrats – you now have a custom class that dispatches events of it’s own, and a handler that takes that event and displays the new temperature. Any other objects that have registered for the change event will know that it changed, but how will they know what it changed to? In the example above, our event handler asks the thermometer for the temperature each time it handles the event. Though, there is another way – we could have the event being dispatched tell the handler about the change itself. To do this, we’ll need to create a custom event.

Custom Events

Continuing with our thermometer example, we’ll now create a custom event, and call it TemperatureEvent. This new event will function just like a regular Event, but it will also contain some information about the temperature changes. To create a custom event, we’ll extend the Event class.Picture 2.pngAs you can see, there’s really not a lot of code here. Essentially, all we’re doing here is storing the new temperature that was the cause of the event being dispatched, and the previous temperature.In our application, we’ll make some changes to handle this event. We’ll update the Thermometer object to dispatch the new TemperatureEvent, and update our application to handle one of those objects.Here we’ll dispatch the new TemperatureEvent:Picture 3.pngRather than create an instance of Event, we’re creating an instance of our new TemperatureEvent class, and passing the temp and prevTemperature variables as parameters to the constructor of the TemperatureEvent. We finish by dispatching our new event.Handling this new event is just like handling any other event:Picture 4.pngAgain, the only difference is that we’re receiving a TemperatureEvent instead of an Event. Now, instead of asking the Thermometer for the temperature, we get that info directly from the TemperatureEvent. We’ve also built the TemperatureEvent so that it can store the previous value of the Thermometer. This way, we not only know that the temperature changed, but by how much.This post has had some basic stuff in it this week, but while being basic it’s a core part of working with ActionScript 3.0. Hopefully, you should have a basic understanding of how to handle the events dispatched by the Flash Player. You should also begin to understand how to create and dispatch your own events – both native Event objects, as well as custom events you have created.The next post in this series will cover some more advanced topics regarding Events, including the Event Flow, the best ways to unregister event listeners, the priority of events, default behaviors, and more.

By: Josh Buhler Categories: flash / flex

Comments are closed.