<

[Webinar] Streamline your web hosting managementRegister Today

x

AS3 Migration: Events

Published on
5,958 Points
2,858 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

Get your problem seen by more experts

Be seen. Boost your question’s priority for more expert views and faster solutions

Join & Write a Comment

The goal of the tutorial is to teach the user how to how to load their YouTube profile onto Flash Media Live Encoder.
The goal of the tutorial is to teach the user how to select the video input device. Make sure you have an input device that in connected and work and recognized by Adobe Flash Media Live Encoder and select it in the “video input” menu.
Suggested Courses
Course of the Month7 days, 23 hours left to enroll

Keep in touch with Experts Exchange

Tech news and trends delivered to your inbox every month