Events

ActionScript 1.0   2.0     3.0  
Flash Player 4 5 6 7 8 9 10

Evolution of ActionScript Events

Events indicate when something happen.  Clicking on a button indicates a "click" event.  When an external text file loads into Flash Player, there's a "complete" event indicating that the contents of that text file have been completely read into the player.

Virtually all ActionScript is executed based on events.  Whether it's an event handler used to run code when a button is clicked or just commands written on the timeline in frames (executed during the event of Flash Player displaying that frame), you're writing code that reacts to events.

ActionScript 1.0 Events

For non frame-based actions, most events (specifically mouse and keyboard events) were originally handled within on([event]){} code blocks placed on button symbols.

// Starting with Flash 2 and available for
// ActionScript 1 and 2, a press event
// placed on a selected button symbol
on(press) {
 	// play timeline in which this button exists
	play();
}

Events used with on (some introduced after Flash 2) include:

  • press
  • release
  • releaseOutside
  • rollout
  • rollover
  • dragOut
  • dragOver
  • keyPress ["whichKey"]

When Flash 5 came around, ActionScript featured a new kind of event handler that could be added, not to button symbols, but movie clips. This was done using the onClipEvent([event]{} code block.

// Flash 5; ActionScript 1
// Placed on a selected movie clip symbol
onClipEvent(enterFrame) {
	// move this movie clip 5 frames to
	// the right every time Flash Player
	// draws a frame based on the frame rate
	_x += 5;
}

With Flash 5 you could also load XML into Flash Player with the new (at the time) XML object.  In order for a programmer to know when the XML has been loaded and parsed, an onLoad event handler would be defined for the XML object.  This handler was in the form of a dynamic function definition that could be defined, deleted and changed for the XML object at any time.

// Flash 5; ActionScript 1
// XML onLoad handler
var myXML = new XML();
// event handler called when
// XML has been loaded into myXML
myXML.onLoad = function(success){
 	// if XML has been loaded and parsed
	// successfully, success is true 
	if (success){
		trace(this);
		// trace XML
	}
}
// load the XML into the XML object when
// loaded and parsed, onLoad will be called
myXML.load("xmlFile.xml");

Flash MX (6) greatly improved event handling. Not only were on code blocks allowed to be used on both movie clips and buttons (as opposed to just buttons) but, Flash MX also allowed dynamic event handlers to be created for buttons and movie clips in the same way the onLoad event handler was defined for XML objects in Flash 5.  Whereas on and onClipEvent were static and couldn't be changed during runtime, using these function-based event handlers meant an event could be deleted or redefined as the Flash movie was playing, something especially useful for onEnterFrame events used to handle animation.

// Flash MX; ActionScript 1
// onEnterFrame event handler
// assigned for for a movie clip instance
myBall_mc.onEnterFrame = function(){
 	// move this movie clip to the right
	// by 5 pixels every frame
	this._x += 5;
	// if the x position of this movie clip
	// is greater than 200, delete the event handler
	if (this._x > 200){
		delete this.onEnterFrame;
	}
}

More importantly, Flash MX introduced a new concept to ActionScript called listeners.  Listeners are objects with methods (and, later, can include just methods or functions) that listen for and have a handler called as a result of an event. The key concept behind listeners is that you can have more than one event handler associated with any one event.  With normal event handlers, like the onLoad event handler with the XML object, you can only define one onLoad function. If you define it again, you will be overwriting the old onLoad and replacing it with the new definition.  It was very difficult to have more than one event handler associated with a single event. Listeners solved that problem.

With listeners, instead of defining an event handler for the object receiving the event, you assigned the event handler to another object – any other object – and then that object was added as a listener of the object originally receiving the event.

// Flash MX; ActionScript 1
// Mouse listeners; more than one
// object/handler reacting to the same event
var handler1 = new Object();
handler1.onMouseDown = function(){
 	trace("Handler 1");
}
var handler2 = new Object();
handler2.onMouseDown = function(){
 	trace("Handler 2");
}
Mouse.addListener(handler1);
Mouse.addListener(handler2); // Clicking the mouse once results in the traces:
// Handler 1
// Handler 2

Since both handler1 and handler2 in the example above were listeners of the Mouse object, their onMouseDown methods were called as event handlers of the Mouse's onMouseDown event. If you ever wanted to remove an object from being an event listener, you could use removeListener().

Assigning listeners with addListener was a great concept but was limited to a few objects. They included:

  • Key
  • Mouse
  • Selection
  • Stage
  • TextField
  • FStyleFormat

ActionScript 2.0 Events

Enter ActionScript 2 with Flash MX 2004 (7).  With ActionScript 2 came a new set of components that used an architecture known as V2 ("Version 2").  This architecture used a new kind of listener format which was similar to using addListener but instead of adding objects as listeners of other objects, you listened to specific events from other objects.  This used a new method called addEventListener that was part of a new (V2) class called EventDispatcher.  The addEventListener method accepted both an object with event handlers (or just an event handler function) as well as a name of the event you wanted to listen for.  The inclusion of the event prevented unnecessary events to be sent to objects that didn't have event handlers for them (e.g. handler1 and handler2 in the previous example received onMouseDown and onMouseUp events from the Mouse object even though they had no event handlers for them). Additionally, an event object was passed to the event handlers added as listeners when called for an event to provide information about the event occuring.

// Flash MX 2004; ActionScript 2
// button component event handlers
// Listener object with event handler
var handlerObject:Object = new Object();
handlerObject.click = function(event:Object):Void {
 	trace(event.type +": "+ this);
}
// Listener function
function handlerFunction(event:Object):Void {
 	trace(event.type +": "+ this);
}
// assign to be listeners of 
// submit_button for the click event
submit_button.addEventListener("click", handlerObject);
submit_button.addEventListener("click", handlerFunction);
// Clicking the submit_button component:
// click: _level0.submit_button
// click: [object Object]

Because this form of event handling was built into the V2 component architecture (the EventDispatcher class being part of that architecture), you really didn't see it much anywhere else in ActionScript outside of components.  The core language objects like Mouse and Key still used the older addListener method for handling events.  This all changed with ActionScript 3.

ActionScript 3.0 Events

ActionScript 3 completely revamped the way events were handled in ActionScript.  There are two major themes that define ActionScript 3 events:

  1. Consistent event handling with a new, native EventDispatcher class
  2. Support for event propagation within display objects

Though the EventDispatcher class is not entirely new having existed with the V2 component architecture present in Flash MX 2004 components, with ActionScript 3 EventDispatcher has been updated and made a native part of the ActionScript language responsible for essentially all event handling.  What does this mean for events in ActionScript 3?

  • No on(event){}
  • No onClipEvent(event){}
  • No adding scripts on selected objects. Period.
  • No object.onEvent = function(){} (for native events)
  • No addListener
  • No object-based listeners (now only using methods/functions)

With ActionScript 3 all event handlers are associated with events using addEventListener and consist of a single function listener. With Events in ActionScript 3 you get the flexibility of listeners (more than one handler for any one event) and the efficiency of the V2 addEventListener (being able to single out events) plus an increase in performance as a result of the EventDispatcher class now being native to Flash Player.

Also, in ActionScript 2, when an event handler was called, it received an Object argument (of the type Object) containing some information about the event such as the type of event and any properties that might be specific to that event.  ActionScript 3 formalized this process now having pre-defined Event classes to be used within events instead of the generic objects used with ActionScript 2.  These event objects contain the event type, where the event originated, the current object receiving the event, as well as a few other properties used to describe the event that occurred.

Different kinds of events have different kinds of Event classes. The most basic event class is Event, but there are also other Event classes such as MouseEvent, KeyboardEvent, and many others.  These classes often also contain the event types as constant properties of the class.  The click event, for example, has an event type of "click" which is defined in the MouseEvent class as MouseEvent.CLICK.  The purpose of using these values instead of their string representations is that the ActionScript compiler will be able to warn you about spelling mistakes if you make them.

button.addEventListener("clikc", handler); // no error
button.addEventListener(MouseEvent.CLIKC, handler); // Error!

To summarize, event handling in ActionScript 3 means:

  • using addEventListener/removeEventListener
  • listening for event types stored in Event classes
  • using a function (not an object) event handler/listener
  • defining event handler/listeners to receive an argument of the type Event
// ActionScript 3 event handler
function clickSubmit(event:MouseEvent):void {
 	gotoAndStop("submitFrame");
}
// add clickSubmit event handler as listener of the 
// click event received by submit_button instance
submit_button.addEventListener(MouseEvent.CLICK, clickSubmit);

Along with how event handlers are defined, you will also changes in how they work and how they are identified. Many event names have changed while other events have been added and even some removed. Here is a quick comparison of some common events between ActionScript 2 and ActionScript 3.

Common Interactive Events
ActionScript 2 ActionScript 3 Differences
onPress "mouseDown" (MouseEvent.MOUSE_DOWN) No notable differences
onRelease "mouseUp" (MouseEvent.MOUSE_UP), "click" (MouseEvent.CLICK) The click event is most like onRelease since it depends on the object first receiving a mouseDown event whereas mouseUp can occur regardless of what was pressed
onReleaseOutside "mouseUp" (MouseEvent.MOUSE_UP) This has been removed, but using the mouseUp event with the stage (because of propagation) will allow you to detect when the mouse has been released outside of the object originally pressed
onRollOver "mouseOver" (MouseEvent.MOUSE_OVER), "rollOver" (MouseEvent.ROLL_OVER) Two events can now be used for rolling over objects; mouseOver will propagate, rollOver will not
onRollOut "mouseOut" (MouseEvent.MOUSE_OUT), "rollOut" (MouseEvent.ROLL_OUT) Two events can now be used for rolling off of objects; mouseOut will propagate, rollOut will not
onDragOver "mouseOver" (MouseEvent.MOUSE_OVER), "rollOver" (MouseEvent.ROLL_OVER) Detecting a "drag" will have to be done manually in combination with the mouseDown event.
onDragOut "mouseOut" (MouseEvent.MOUSE_OUT), "rollOut" (MouseEvent.ROLL_OUT) Detecting a "drag" will have to be done manually in combination with the mouseDown event.
mouseDown "mouseDown" (MouseEvent.MOUSE_DOWN) Now only works when the mouse is over the object dispatching the event (like onPress); normal objects cannot be made listeners of the Mouse to be able to recieve this event, only InteractiveObject instances can
mouseUp "mouseUp" (MouseEvent.MOUSE_UP) Now only works when the mouse is over the object dispatching the event (like onRelease but not requiring that the object be clicked first); normal objects cannot be made listeners of the Mouse to be able to recieve this event, only InteractiveObject instances can
mouseMove "mouseMove" (MouseEvent.MOUSE_MOVE) Now only works when the mouse is over the object dispatching the event; normal objects cannot be made listeners of the Mouse to be able to recieve this event, only InteractiveObject instances can
onKeyDown "keyDown" (KeyboardEvent.KEY_DOWN) Object must now have focus to receive this event; normal objects cannot be made listeners of the Key to be able to recieve this event, only InteractiveObject instances can
onKeyUp "keyUp" (KeyboardEvent.KEY_UP) Object must now have focus to receive this event; normal objects cannot be made listeners of the Key to be able to recieve this event, only InteractiveObject instances can

You may notice a theme of reducing the number of events needed to work with in ActionScript. The older onPress and onMouseDown events have now been consolidated into one mouseDown event in ActionScript 3. Similarly, you are seeing events that are less global and more specific to a related object. The mouseMove event, for example, now only works when the mouse is over the object handling the event. Similarly, the key events, too, only respond to the objects which currenly have focus.

Other behaviors regarding mouse events and display objects have also changed. In ActionScript 2, for example, adding any onPress, onRelease, or similar "on" mouse event handler to a movie clip would cause that movie clip to display a hand (or finger) cursor when the mouse was over that movie clip. This is no longer the case with ActionScript 3. That hand cursor will now not be visible unless the display object's buttonMode and useHandCursor properties are true (useHandCursor is true by default but buttonMode is not). Setting buttonMode to true will also enable a focused object to receive a click event if the space bar or the Enter key is pressed on the keyboard.

// Show the hand cursor for myButton
// and allow clicking through Spacebar and Enter
myButton.buttonMode = true;

Similarly, by defining the same event handlers in ActionScript 2 that provided the hand cursor, you were also indicating to Flash Player that the movie clip was "mouse enabled" or that it is necessary for that instance to intercept and handle mouse events. Movie clips without those "on" mouse event handlers ignored mouse events and let them pass on through to any mouse enabled movie clip instances beneath them. With ActionScript 3, all mouse capable display objects (any instance on the screen that inherits from the InteractiveObject class, including Sprites and MovieClips) will be mouse enabled by default and prevent events from reaching instances arranged below them, even if they have no event handlers defined for them. To change this, you have to set the object's mouseEnabled property to false.

// Allow objects beneath the overlay
// instance to receive mouse events
overlay.mouseEnabled = false;

There's a similar mouseChildren property which relates to child objects within a display object container instance. When mouseChildren is set to false, child objects will not receive mouse events but the main parent object will (assuming mouseEnabled is true). This becomes useful when dealing with event propagation.

// Prevent the child objects in the
// window instance from receiving mouse events
window.mouseChildren = false;