ActionScript 2.0 (AS 2.0) was introduced in the latest incarnation of Flash (Flash MX 2004) and while ActionScript 1.0 (AS 1.0) has been embraced by developers and experimentalists alike, it was never a true object oriented language -– it was more object-based. As such, it didn’t attract the attention of mainstream application developers. AS 2.0, on the other hand, is much like other object orientated languages such as C# and Java, which use the new ECMA JavaScript 2.0 standards.
This makes it easier to develop more scaleable, robust and modular projects.
In AS 1.0, creating prototypes to extend functionality was more of a learned process than logical one. And, if you accidentally converted from one data type to another (number to string or vice versa), although the application may have worked, any errors would not have been reported back via the Output Panel.
Let’s briefly discuss the major enhancements in ActionScript 2.0 before we look at some simple, real world AS 2.0 examples in action. Note that you can download the source files for this tutorial.
Key Takeaways
- Introduction of Strong Data Typing: ActionScript 2.0 enforces strong data typing, requiring developers to declare the data type of variables, which enhances error checking and reduces runtime errors.
- Case Sensitivity: Unlike AS 1.0, AS 2.0 treats variable names with case sensitivity, which means similar named variables with different cases are treated as distinct, potentially leading to errors if not managed correctly.
- Class File Management: AS 2.0 mandates that each class be defined in its own external file (.as), with the filename matching the class name, promoting better organization and modular coding practices.
- Improved Object-Oriented Features: AS 2.0 aligns more closely with traditional object-oriented programming languages, offering features like inheritance through the ‘extends’ keyword, enhancing the capability to build complex applications.
- Migration of AS 1.0 Code: Transitioning from AS 1.0 to AS 2.0 involves rewriting code to fit the new object-oriented structure, which allows for more scalable and maintainable codebases.
Strong Data Typing
When creating variables and objects in AS 2.0, you should get into the habit of declaring the data type. This is different from AS 1.0 in that, previously, you could get away with using loosely typed variables that had the knock-on effect of potentially introducing points of failure into your applications.
When you compile your movie or check for script errors in AS 2.0, variable data types are checked and any errors are sent to the Output Panel as error messages. Consider the following code:
var NotANumber:String = 15;
var NotAString:Number = "Fifteen";
This code will output 2 error messages, as the assigned value for the variable NotANumber
is a number, rather than a string. Also, the assigned value for the variable NotAString
is a string, rather than the declared data type of Number
.
It’s a pretty simple procedure, and one that, once you’re in the groove of doing it, becomes second nature.
Case Sensitivity
If you’re not used to coding with case sensitivity in mind, then you might be in for a bit of a shock when your AS 2.0 projects stop working. Consider the following code:
var TextField_001 = "Some Information";
var textfield_001 = "Different Information";
trace(TextField_001);
trace(textfield_001);
If you were to preview the movie within Flash using AS 2.0, you would see both variables within the Output Panel, as they are interpreted as separate variables; in AS 1.0 you would see only one value, as AS 1.0 is largely case insensitive.
Creating AS 2.0 Classes
In AS 1.0, it was considered best practise to externalise your ActionScript
into an external .as
file, rather than including the code within a frame of the timeline. In AS 2.0, this has been taken a step further. When creating new classes, you no longer have a choice — all classes must be located in a separate .as
file.
You can create your .as
files easily using Flash MX 2004 Professional, Notepad, PrimalScript or other such editing tools. You may define only one class per .as
file, and the filename must match exactly the name of the class definition. For example:
class AlphaFade{
// Class Properties, Constructors and Methods go here!
}
The class AlphaFade
must be saved in a file called AlphaFade.as
in your local setting folder. On Windows, the file must be saved in the following location:
[Drive]:Documents and Settings[Username]Local SettingsApplication DataMacromediaFlash MX 2004[Language]ConfigurationClasses
Where:
[Drive] = Installation Drive
[Username] = Your Login Account
[Language] = Flash MX 2004 localization language (usually for International English, it is 'en')
Note: The reason the class files should be saved in your local settings folder is outlined in my Flash blog here.
Property and Method Attributes
Defining a variable or function as private or public dictates the scope in which the method or property is available. If the attribute is noted as private, then it can only be accessed via the class, whereas, if it is noted as public, it can be accessed outside of the class. Consider the following:
public function checkIfEmpty (incomingString:String):Boolean {
if ( incomingString.length == 0)
{
return true;
} else {
return false;
}
}
The function checkIfEmpty()
is a public function, and is accessible from the timeline of the Flash movie via the class (more on this later).
The following variable is only accessible within the class itself:
private var incomingString:String;
Extends Attribute
The extends
attribute (as we will see in a moment) is used to inherit public and private methods or properties from other classes.
In the example below, we can simply extend the MovieClip
class by creating a new class file called ShiftingClip
.
class ShiftingClip extends MovieClip {
// Properties, Constructor, Methods go here
}
Although there are other attributes (dynamic, static, getters and setters) that are important, we’ll discuss them in a later article. Right now, we just need to cover some basic groundwork to get you up and running.
Without explaining all of the AS 2.0 OOP structure, we can now safely move on to see how to construct class files and reference them from within our Flash movies.
Migrating AS 1.0 Functions to AS 2.0 Classes
Whenever a new version of a given programming language comes along, it generally means that the API has been upgraded, new routines have been added, or it has been rewritten.
In the example of AS 2.0, the prototype chaining has been rewritten, among many other things. This engenders a more modular and controlled approach to programming, allowing the development of custom classes and the extension of already-created classes with relative ease.
Thus, we can take Flash 5 syntax or ActionScript 1.0-based code and migrate it without difficulty into the new AS 2.0 OOP environment.
In this example, we will migrate a chunk of validation code from a timeline-based location to an external class file. The code will check to ascertain whether a string has any content, meets a minimum string length and contains numeric content. A Boolean value will be returned, which identifies the conditions that have been met.
Setting the Scene
- Within Flash MX 2004, create a new Flash document, accepting the default size and frame rate.
- Rename the default layer
Actions
, and add another layer below, namedItems
. - Drag three
TextInput
components from the Components Panel into the first frame of theItems
layer, aligning them above one another on the right hand side of the stage. - Drag a further instance of the
TextInput
component from the Components Panel and align it to the right of the previously-addedTextInput
components. Name the instanceusername
. - Create 3 static text boxes, and align them with the top of each of the
TextInput
component instances. Enter the following text into the boxes so that, from top to bottom, they read:'Empty?'
,'Minimum Length?'
and'Numeric Content?'
- Save the Flash document to a location of your choice.
Name the instances from top to bottom:
anyContent
, minLength
, and anyNumeric
.We will use the
username
text area to input data, and the three vertically aligned text areas to provide feedback on the status of the string that we’re checking. Now that we’ve added the relative components to the stage and set the scene, we can take our AS 1.0 code and start the upgrade process to AS 2.0.
Migrating the Code
Shown below is the AS 1.0 version code that we want to migrate to AS 2.0. In the original AS 1.0 version, I used dynamic text boxes to hold the information, but in this version, I’ll use some version 2.0 components, as they’re quicker to set up.
This is a basic, event-driven setup, whereby we have an event listener attached to the username
version 2.0 TextInput
component. When the content of the component changes (i.e. when someone starts to type), the simpleValidation()
function is called. This acts as a wrapper function, calling three validation functions.
The results from these functions are then pushed to the three TextInput
instances, so we can check for numeric content, an empty field, and a minimum required length. It’s nice and simple!
validationListener = new Object();
validationListener.change = function() {
simpleValidation();
};
username.addEventListener("change", validationListener);
function simpleValidation() {
minLength.text = checkStringLength(username.text,10);
anyNumeric.text = checkContainsNumeric(username.text);
anyContent.text = checkIfEmpty(username.text);
}
function checkStringLength(incomingString, stringLength) {
if (incomingString.length >= stringLength) {
return true;
} else {
return false;
}
}
function checkContainsNumeric(incomingString) {
var invalidChars ="1234567890";
for (i=0; i<incomingString.length && containsNumbers == false; i++)
{
var character= incomingString.charAt(i);
if (invalidChars.indexOf(character) != -1)
{
return true;
}
}
return false;
}
function checkIfEmpty(incomingString) {
if(incomingString.length == 0)
{
return true;
} else {
return false;
}
}
What we have here is the ability to quickly convert this AS 1.0-based code into AS 2.0 based classes, to make it more manageable and scalable.
Creating the Class File
The structure for a class file is quite simple; it looks something like this:
class yourClassName {
// Properties
var myString:String;
var myNumner:Number;
var myMovieClip:MovieClip;
// Constructor function
function yourClassName() {
}
// Methods
public function yourFunction(){
}
}
We will create a custom
class file with custom properties, constructors and methods in a moment, so that we can see how a real life class file operates.
- Within Flash MX 2004 Professional (Select File > New > ActionScript File) or a text editor of your choice, create a new file called
Retro.as
.
Note: the editing of external .as
class files within Flash is only supported natively by Flash MX 2004 Professional.
class Retro {
private var incomingString:String;
private var stringLength:Number;
//Constructor
function Retro(incomingString:String) {}
//Methods
public function checkStringLength(incomingString:String,
stringLength:Number):Boolean {
this.incomingString = incomingString;
this.stringLength = stringLength;
if (this.incomingString.length >= stringLength) {
return true;
} else {
return false;
}
}
public function checkContainsNumeric(incomingString:String):Boolean {
this.incomingString = incomingString;
var invalidChars:String = "1234567890";
var i:Number;
for (i=0; i < this.incomingString.length && containsNumbers == false; i++)
{
var character:String = this.incomingString.charAt(i);
if (invalidChars.indexOf(character) != -1)
{
return true;
}
}
return false;
}
public function checkIfEmpty(incomingString:String):Boolean {
this.incomingString = incomingString;
if (this.incomingString.length == 0)
{
return true;
} else {
return false;
}
}
}
Retro.as
to your local settings folder, or in the same directory as your FLA:[Drive]:Documents and Settings[Username]Local SettingsApplication DataMacromediaFlash MX 2004[Language]ConfigurationClasses
Where:
[Drive] = Installation Drive
[Username] = Your Login Account
[Language] = Flash MX 2004 localization language (usually for International English, it is 'en')
Now that we’ve created the external class file, let’s take a look at how it fits together.
First, we create the class name Retro
and define some simple private properties.
Note that the constructor function Retro()
shares the same name and case as the defining class, and is necessary for extra flexibility within the class.
It also accepts an incoming parameter of the data type String, called incomingString
.
class Retro {
private var incomingString:String;
private var stringLength:Number;
//Constructor
function Retro(incomingString:String) {}
We then move on to the methods of the class, in this case, a public function called checkString()
. This accepts two incoming parameters: incomingString
, the data type for which is String
, and stringLength
, which has a data type of Number.
public function checkStringLength(incomingString:String, stringLength:Number):Boolean {
In addition to the incoming parameters, we also define the data type of the data that’s returned as Boolean
.
From there, we define the properties of the class using the this.keyword
syntax:
this.incomingString = incomingString;
this.stringLength = stringLength;
This value is used to check for valid data. In this case, we check that the length of the incomingString
variable is greater than, or equal to, the stringLength
variable. We then return the value of the public function to the callee
(which we will add in a moment).
if(this.incomingString.length >= this.stringLength){
return true;
} else {
return false;
}
}
The other methods in the class follow similar rules, but check for missing and numeric content, so we can skip over them.
Adding the ActionScript
Now that we’ve created the external class file, all that remains is to add the code that hooks into the class – then, we can test the functionality!
- Select the first frame of the Actions layer in your FLA, and add the following code to the Actions Panel:
var validateMe:Retro = new Retro();
validationListener = new Object();
validationListener.change = function() {
simpleValidation();
};
username.addEventListener("change", validationListener);
function simpleValidation() {
minLength.text = validateMe.checkStringLength(username.text, 10);
anyNumeric.text = validateMe.checkContainsNumeric(username.text);
anyContent.text = validateMe.checkIfEmpty(username.text);
}
You can see (from the bold code) that we’ve created a new reference to the class file, called validateMe
. When the value within the box changes, we call the simpleValidation()
wrapper function, as we did in the AS 1.0 function. Then, as before, we push the return values of the functions to the relevant TextInput
instances.
Before you start typing in the text box, you should see that the three feedback text areas contain no information. As soon as you start typing, the change event handler is triggered and content of the text box is sent to the three public functions. Their return values are returned to the relevant feedback area.
If you add more than 10 characters to the text area, the minimum content length trigger changes from false to true (try changing the value in the following line to alter the minimum length).
validateMe.checkStringLength(username.text,10);
If you add numeric content into the field, this also will be fed back within the SWF from the checkContainsNumeric()
method.
There you go! It really wasn’t that hard to migrate our AS 1.0 code to scalable, reusable and portable AS 2.0 code after all.
You may be sitting there thinking, why would I want to write anything in AS 2.0? What are the benefits? The main reasons for upgrading your existing code from AS 1.0 to AS 2.0, or writing your new applications in AS 2.0, hinge around modularity, reusability and scalability, not to mention the fact that developing code in an object orientated programming language will help you develop better coding practices.
If we wished to create a series of classes to extend the functionality of the MovieClip
class and allow a dynamic opacity fade, we could create the following .as
file, saved as FadeClip.as
, as follows:
class FadeClip extends MovieClip{
//Properties
private var MCName:MovieClip;
private var currentAlpha:Number;
private var differenceAlpha:Number;
private var fadeStep:Number;
private var endPosition:Number;
private var stepSize:Number;
//Constructor
function FadeClip() {}
//Methods
public function AlphaFade(MCName:MovieClip, startAlpha:Number, finalAlpha:Number) {
currentAlpha = MCName._alpha;
differenceAlpha = finalAlpha-currentAlpha;
fadeStep = differenceAlpha / 10;
MCName._alpha = MCName._alpha + fadeStep;
}
}
As the public function AlphaFade()
accepts a MovieClip
parameter, as well as starting and final alpha parameters, we can easily fade any given MovieClip
from one value to another. To achieve this, we’d add the following code to a frame on the timeline.
Note: This code references a MovieClip
instance within the timeline named TitleToAnimate
.
var fader:FadeClip = new FadeClip();
_root.onEnterFrame = function() {
fader.AlphaFade(TitleToAnimate, 10, 100);
}
By setting the _alpha
property of the TitleToAnimate MovieClip
instance to an arbitrary value of 10, we can fade the opacity from a starting value (10) to the final value (100).
AS 2.0 migrations seems to scare a lot of people, but, once you get started, you never look back! It’s as easy as falling off a bike … almost!
Frequently Asked Questions about ActionScript Migration Basics
What is the difference between ActionScript 2.0 and ActionScript 3.0?
ActionScript 2.0 and ActionScript 3.0 are both scripting languages used in Adobe Flash. However, ActionScript 3.0 is a more advanced version with improved performance and better object-oriented programming support. It also has a more robust API and supports advanced features like 3D graphics and file uploads. On the other hand, ActionScript 2.0 is simpler and easier to learn, but it lacks some of the advanced features of ActionScript 3.0.
How can I migrate from ActionScript 2.0 to ActionScript 3.0?
Migrating from ActionScript 2.0 to ActionScript 3.0 involves several steps. First, you need to understand the differences between the two versions. Then, you need to rewrite your code to comply with the new syntax and features of ActionScript 3.0. This may involve changing the structure of your code, updating function calls, and replacing deprecated features with their new equivalents.
What are the benefits of migrating to ActionScript 3.0?
Migrating to ActionScript 3.0 offers several benefits. It provides better performance, more powerful programming features, and access to advanced APIs. It also allows you to take advantage of the latest developments in the Flash platform, such as 3D graphics and file uploads.
What challenges might I face when migrating to ActionScript 3.0?
Migrating to ActionScript 3.0 can be challenging, especially if you have a large codebase written in ActionScript 2.0. You may need to rewrite a significant portion of your code to comply with the new syntax and features. Additionally, you may need to learn new programming concepts and techniques.
Are there any tools that can help me migrate to ActionScript 3.0?
Yes, there are several tools that can help you migrate to ActionScript 3.0. For example, Adobe offers a migration guide that provides detailed instructions and examples. There are also third-party tools and libraries that can automate some of the migration process.
Can I still use ActionScript 2.0 after migrating to ActionScript 3.0?
Yes, you can still use ActionScript 2.0 after migrating to ActionScript 3.0. However, you may not be able to take advantage of some of the new features and improvements in ActionScript 3.0.
How long does it take to migrate to ActionScript 3.0?
The time it takes to migrate to ActionScript 3.0 depends on the size and complexity of your codebase. It can take anywhere from a few days to several weeks or even months.
What are some best practices for migrating to ActionScript 3.0?
Some best practices for migrating to ActionScript 3.0 include understanding the differences between the two versions, planning your migration carefully, testing your code thoroughly, and using tools and resources to help with the migration process.
Can I migrate to ActionScript 3.0 incrementally?
Yes, you can migrate to ActionScript 3.0 incrementally. This means you can update parts of your codebase to ActionScript 3.0 while leaving other parts in ActionScript 2.0. This can make the migration process more manageable.
What should I do if I encounter problems during the migration process?
If you encounter problems during the migration process, you should seek help from the Adobe community or other online resources. You can also hire a professional developer or consultant to assist with the migration.
Steven is cofounder of phireworx.com, a Fireworks resource site, and contributing author of Fireworks MX Magic (New Riders), Special Edition Using Fireworks MX (Que), and Fireworks MX Fundamentals (New Riders). Steve wrote SitePoint's The Flash Anthology: Cool Effects & Practical ActionScript