<

Go Premium for a chance to win a PS4. Enter to Win

x

AS3 Migration: Events

Published on
5,913 Points
2,813 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

[Webinar] Cloud and Mobile-First Strategy

Maybe you’ve fully adopted the cloud since the beginning. Or maybe you started with on-prem resources but are pursuing a “cloud and mobile first” strategy. Getting to that end state has its challenges. Discover how to build out a 100% cloud and mobile IT strategy in this webinar.

Join & Write a Comment

In this tutorial viewers will learn how to create a basic shape tween animation in Flash including shape hints for smooth animation Open a new document in Flash: Draw a shape: Select another frame (how long you want the tween to be): Right click and…
The goal of the tutorial is to teach the user how to use the auto adjust feature and what the different options do. When your video is not working right you can choose the auto adjust feature to help choose your settings.
Suggested Courses

Keep in touch with Experts Exchange

Tech news and trends delivered to your inbox every month