<

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x

AS3 Migration: Events

Published on
6,142 Points
3,042 Views
1 Endorsement
Last Modified:
This is a very simple example to help those of you who are still migrating from AS2 to AS3 understand the redesigned event model in AS3.

In AS2.0, event functions (that is, the function to be performed when an event is fired) were stored as a property of the function's caller. Hence, a "button clicked" function would be accomplished by

 
// AS2.0 code
myButton.onPress = function() {
	trace("button clicked")
};

Open in new window


in AS3.0, however, event functions are stored externally as independent functions, and only event listeners (something that checks to see if an event has happened) are attached to the caller itself.

Therefore, the above code snippet would translate as follows:

 
//AS3.0 code
import flash.events.MouseEvent;
// ...
myButton.addEventListener(MouseEvent.CLICK, clickFunction);

function clickFunction(e:MouseEvent) {
	trace("button clicked");
}

Open in new window


A few notes about this new event model

1: You need to import every type of event you will be calling. A few of the most common events include MouseEvent, TimerEvent, and just plain Event. If you want to play it safe, import flash.events.* (that will import all events).

2: The first parameter of your event function (clickFunction in this case) MUST be the type of event that the function is responding to. Also note that all events subclass Event, so the parameter (e:Event) will always work as long as you have imported Event.

3: Also, keep in mind that regardless of what event triggers the function, the function will ALWAYS be called from where it is defined in the code. That is, if you define a function on the main timeline and add a click listener to a button on the stage, trace(this) will return [object MainTimeline].
1
Comment
Author:Vega152
0 Comments

Featured Post

PMI ACP® Project Management

Prepare for the PMI Agile Certified Practitioner (PMI-ACP)® exam, which formally recognizes your knowledge of agile principles and your skill with agile techniques.

Join & Write a Comment

The goal of the tutorial is to teach the user how to live broadcast using Flash Media Live Encoder and connecting it to YouTube to broadcast. Log into your Youtube account, choose live stream settings, start live stream from Flash Media Live Enc…
The goal of the tutorial is to teach the user how to select which audio input to use. Once you have an audio input plugged into the laptop or computer, you will go into the audio input settings and choose which audio input you want to use.

Keep in touch with Experts Exchange

Tech news and trends delivered to your inbox every month