Migrate ActionScript 1.0 to ActionScript 2.0 , Part 1: The Basics

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.

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


[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

Migrate ActionScript 1.0 to ActionScript 2.0 , Part 1: The Basics

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

  1. Within Flash MX 2004, create a new Flash document, accepting the default size and frame rate.
  2. Rename the default layer Actions, and add another layer below, named Items.
  3. Drag three TextInput components from the Components Panel into the first frame of the Items layer, aligning them above one another on the right hand side of the stage.

    Name the instances from top to bottom: anyContent, minLength, and anyNumeric.
  4. Drag a further instance of the TextInput component from the Components Panel and align it to the right of the previously-added TextInput components. Name the instance username.

    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.
  5. 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?'
  6. Save the Flash document to a location of your choice.

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.

  1. 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.
  2. Add the following code:
    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;       }     }   }
  3. Save 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


[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!

  1. 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.

  2. Save your FLA and select Control > Test Movie.

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).


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!


Category: software Time: 2004-06-22 Views: 1

Related post

iOS development

Android development

Python development

JAVA development

Development language

PHP development

Ruby development


Front-end development


development tools

Open Platform

Javascript development

.NET development

cloud computing


Copyright (C) avrocks.com, All Rights Reserved.

processed in 0.115 (s). 12 q(s)