Welcome!

You will be redirected in 30 seconds or close now.

ColdFusion Authors: Yakov Fain, Jeremy Geelan, Maureen O'Gara, Nancy Y. Nee, Tad Anderson

Related Topics: ColdFusion

ColdFusion: Article

Ramping Up on Flash MX 2004 and ActionScript 2.0

Ramping Up on Flash MX 2004 and ActionScript 2.0

I could not be more excited about the release of Flash MX 2004 and the new ActionScript 2.0. This new version of ActionScript has taken a huge leap in standardizing a more object-oriented programming structure to its syntax and has given the developer the ability to catch many more errors at compile time than in ActionScript 1.0.

For many developers, this advancement will help increase development time and quality of code. Some of the language's feature enhancements include strong data typing, a more standard way of class declarations, inheritance, interfaces, packages, and error handling.

Before I go into the new features of ActionScript 2.0, let's investigate some of the sources to the core classes that get installed. On my computer they are located in [installation dir]/Macromedia Flash MX 2004/First Run/Classes/. Looking at these real-world examples is an invaluable source for research and development. Though I would caution not to change these files, you may even consider doing a backup of this folder first.

The help files that can be accessed from the main menu under "Help" within Flash MX 2004 contain some good information on creating classes, and cover the new language features in an incremental manner. So I did not want to do a rehash of that here. Instead, I want to cover the new adjustments that I needed to make in order to begin coding with the new Flash MX 2004 environment and ActionScript 2.0 language.

Ramping up on the new features and getting comfortable with all of the IDE and language changes was actually a larger task than I expected. In the first place, there are many new ways that you can approach an application in Flash MX 2004. For instance, you can create a Flash Document, Flash Slide Presentation, Flash Form Application, or Flash Project (note: Flash Slide Presentation, Flash Form Application, and Flash Project are available only in Flash MX Professional 2004).

The Flash Slide Presentation and Flash Form Application are options that allow you to work on an application that's similar to a Visual Basic IDE, where you would organize your work into logical screens (forms). Although I intend to investigate this new way of developing Flash applications, I did not start here. A Flash Project is a great tool. By creating a Flash Project you attach relevant files, which allows for quick access and organization with external files (see Figure 1). The Flash Document is in Flash MX 2004 and Professional edition and is the most similar to the method used to develop in Flash MX.

 

Before I started my application, I needed to understand some differences between ActionScript 1.0 and 2.0. First, which player supports 2.0? Flash Player 6 and 7 both support ActionScript 2.0, but Flash Player 6 is missing some features like try/catch error handling and others. However, in general, Flash Player 6 supports the core of ActionScript 2.0. This is a good thing, because it will take awhile for general users to upgrade to Flash Player 7 and corporate IT managers to approve a company-wide change.

Next, I began to look at the syntactic differences. The first thing I saw was the strict data typing of variables. Now you can declare variables with a type as follows:

[var] variableName:[type]

example:
// declaring a string variable
var myString:String = "test";

// declaring a variable from an object I defined
var myObj:MyObject = new MyObject();

When declaring variables you start with the keyword "var", then put the variable name followed by a ":" and a type, which is any native data type or a class or interface you have defined. One thing I have left out in this example is the ability to add scope to your variable definition. I will be addressing this topic later in the article.

Strict data typing is a very big change for ActionScript developers, and I am aware that some developers will be adverse to this change, but in the long run, the headaches solved by this new rule will outweigh the effort that was needed to implement it. For example, if you use a variable incorrectly, the compiler tells you. Think about the power of this in the scope of day-to-day development and how much debugging time will be saved. To illustrate, try adding a number and a string (see Figure 2).

 

In the previous version of Flash MX, the compiler would continue to compile without warnings or breaking. Now, you'll get the following error:

**Error** Scene=Scene 1, layer=Layer 1, frame=1:Line 4:
Type mismatch in assignment statement: found String where Number is required.
myNum = myNum + myString;

Total ActionScript Errors: 1 Reported Errors: 1

This language feature is my number one language enhancement.

The second difference is in the way that classes were defined. Previously in ActionScript 1.0 a class would be defined using the prototype chaining method like this:

MyClass = function() {
}

Then you would write methods like this:

MyClass.prototype.init = function() {
}

Now with ActionScript 2.0, classes are defined as follows:

class MyClass {
// methods are defined within the class
function myMethod() {
}

}

Define your classes in an external file with the .as extension. Each class definition must be in its own file so you have only one class per file. The file name must be the same as the class name (MyClass.as). Also, unless you change the classpath settings in the ActionScript preferences, keep your class files relative to your .fla. You can organize your code into packages by saving the files in subdirectories and declaring the class with the subdirectory path:

// package support in ActionScript 2.0
class com.iindwell.MyClass() {

}

The path to this file would look like this:

[.fla location]/com/iindwell/MyClass.as

Once you have defined your class, you can make references to that class by importing and instantiating it. In ActionScript 1.0, I would use the #include statement to get references to class definitions. However, in ActionScript 2.0 you'll use import.

// code contained in SomeOtherClass.as
import com.iindwell.MyClass

class SomeOtherClass {
function myMethod() {
var foo:MyClass = new MyClass();
}
}

Without going too deep into object-oriented theory and definitions, I'll list some of the new class features.

Constructor
Classes now have constructors that get called automatically when a class is instantiated. A class constructor must be named the same as the class name.

class MyClass {
function MyClass () {
// this method will be called automatically when instantiated
}
}

New Scope
Public, Private, and Static variable and method scope will give you much more control over how your variables can be accessed. Public variables and functions are the default scope and allow access to any class that calls it. Private variables and functions allow access only to the class that they are defined in. Here's a Private and Public example:

class MyClass {
private var myString:String;
// only to the class that declares or defines it, or to subclasses of that class
public var myNum:Number;
// available to any class that calls it
var myNum2:Number;
// by default, instance variables are public by just declaring them with var

function MyClass () {
// declaring variables within a function keeps them private to that method
var myDate:Date = new Date();

}
}

Static variable and functions are a little more tricky. Static means that it is only declared once and is used by every instance of that class. This means if you set a counter variable as static, and increment it by one in the class constructor, the counter variable will increase every time you create a new instance of that class.

To illustrate the static scope example try the following:

  1. Create a Flash document and save it (you can name it whatever you like).
  2. In the same directory you saved the Flash document create a file named: StaticExample.as
  3. In the StaticExample.as file put in the following code:

    class StaticExample {
    static var counter:Number = 0;
    function StaticExample() {
    counter++;
    trace("Number of StaticExample instances = " + counter);
    }
    }

  4. Now in the first frame of your Flash document put in the following code:

    import StaticExample;

    var test1:StaticExample = new StaticExample();
    var test2:StaticExample = new StaticExample();
    var test3:StaticExample = new StaticExample();
    var test4:StaticExample = new StaticExample();

  5. Run your Flash Document. Your output window will look like this:

    Number of StaticExample instances = 1
    Number of StaticExample instances = 2
    Number of StaticExample instances = 3
    Number of StaticExample instances = 4

Get/Set
Many languages have adopted the practice of setting up "accessor" methods to retrieve and set the values of private variables within a class. Accessor methods are great for hiding the process that is taking place when values are set in a class. When creating a class definition, some of your data may need to be formatted every time the property is set or retrieved, so by not allowing access to the variable that holds the data, and forcing the use of a get/set method, you're guaranteed that property will be formatted as needed.

In ActionScript 2.0 you can currently write accessor methods in two ways. The first (shown in the first example) is the traditional route where you write methods as you would any other method and call the method in the same way as well. The second way (shown in the second example), would be by using the set/get keywords in your method declaration to act as a shortcut when accessing those properties.

First Example (traditional way):

var user:User = new User();
user.setName("Curtis");
var username = user.getName();

While the class definition of User would look like this:

class User() {
private var _username:String;

function setUsername(name:String) {
_username = name;
}
function getUsername():String {
return _username;
}
}

Second Example (new get/set feature):
Here's how it would look using the implicit getting or setting with the get/set feature:

var user:User = new User();
user.username = "Curtis";
var username = user.username;

New class definition using get / set feature:

class User() {
private var _username:String;

function set username(name:String) {
_username = name;
}
function get username():String {
return _username;
}
}

As you can see, with the get/set feature of ActionScript 2.0 you can access your properties by using a shortcut and just typing in the property name that was defined in your get/set method declarations. Depending on your personal preference, this new method can make your code appear to be cleaner and more standardized.

Inheritance
Reusing code is a major goal in software development. Using the extends keyword in a class definition will allow that class to inherit another class's properties and methods. "Inheriting" another class's functionality will save time on development and maintenance fixes. A shopping cart Web site example illustrates the difference between a shopper and an administrator of the Web site.

Both are users, yet they function very differently. Specifically, they both have profiles created in the system that contain a username and password. The shopper has many different properties that contain address and credit card info, while the administrator does not. The administrator user would contain report preferences and access levels to data roles. So, in order to get the best code reuse out of these two types of users we can take the similarities and make a parent object User.

class User() {
private var _username:String;
private var _password:String;
function set username(name:String) {
_username = name;
}
function get username():String {
return username;
}

function set password(pass:String) {
_ password = pass;
}
function get password():String {
return _ password;
}

}

Then, by extending the User class we can define to subclasses to inherit the User class's properties and methods:

class Administrator extends User() {
// report preference and access code goes here
...
}
class Shopper extends User() {
// address and credit card info goes here
...
}

Both Shopper and Administrator classes can now be instantiated and have the username and password properties of the User class accessible:

var admin = new Administrator();
admin.username = "chermann";
admin.preferredSortOrder = "recent";
var shopper = new Shopper();
shopper.username = "jsmith";
shopper.address = "101 S. Main St.";

When extending another class, keep in mind where the class it is extending resides in the classpath. By default, Flash looks at the document-level classpath set for that FLA (located off the main menu preferences/ActionScript (Tab)/ActionScript 2.0 Settings ... (button)). See Figure 3.

 

Flash will first look in the directory that the compiled .fla is being saved in. If the classpath is not found, then it will look in the global classpath. If the classpath specified is still not found, a compilation error will be generated. If a class needs to extend a class that is in a different package and that parent class's package is in the classpath, just include it in the class definition:

class Administrator extends com.iindwell.User() {
// report preference and access code goes here
...
}

Don't reinvent the wheel. By extending core classes like MovieClip, Math, Window, etc... you can inherit all the power and add functionality by simply extending the class and creating new properties and methods to suit the needs of your application.

Interfaces
Interfaces are used to enforce a class definition. An interface acts like a contract to those classes that implement the interface. Basically, an interface defines functions, not the supporting code, that needs to be defined in the implementing class.

You will create an interface like a class in an external .as file and name the file the same as the interface. The interface looks like a class, but will only have skeleton code like this:

interface DataScreen {
function save():Void;
function refreshData(id:Number);
function isDirty():Boolean;
}

Accordingly, the methods have no supporting code, only a definition. An interface is a way to enforce class definition, instead of an actual class. You implement this definition using the implements keyword in your class to stay compliant to the intended architecture. Consequently, your code must look like this:

class UserInputScreen extends MovieClip implements DataScreen {
function save():Void {
// save code here
}
function refreshData(id:Number) {
// refresh code here
}
function isDirty():Boolean {
// check to see if data has changed here
}
}

As a result, any screen that implements the interface DataScreen guarantees that the class supports these three methods. The above example applies to many business applications that will have multiple data input screens that are loaded into view and controlled by another object, like a menu bar. The menu bar will expect that any active data-input screen has save, refreshData, and isDirty methods. Generally, any developers on the project, when developing a data-input screen, must implement the DataScreen interface. This is valuable when working on large applications or with a team of developers to make sure that every object follows a standard.

Dynamic
Illustrated by the code examples here, ActionScript 2.0 has a strict object-oriented syntax and is not flexible when it comes to breaking the object definition. When using an object in ActionScript 2.0 and attempting to access a property or method that does not exist, an error will occur. This is a good thing. On the other hand, you may encounter a situation where you want to have the flexibility of ActionScript 1.0 and be able to create variables and methods on-the-fly. You can do this by using the dynamic keyword in your class definition.

dynamic class MyDynamicClass {

}

From this point, MyDynamicClass will allow you to create properties and add methods to that class dynamically and any subclass will become dynamic as well. But, by doing this, you are opening yourself up to bugs (e.g., misspelling the intended variable name and referencing it by the correct spelling later in the code will give you two variables in the object, not one) that cannot be detected by the compiler, so keystroke softly.

Moving On
When I develop in Flash, I always keep my source code in external files. Flash MX 2004 really encourages this method. In Flash MX I would include files in the first frame of the movie clip. In contrast, this is not needed anymore. When you create a symbol you have the option of coding all of your ActionScript in an external class file. You must create this file yourself; if you do not, the compiler will generate an error. Flash does not write any code in this file - it's up to you to generate this code. This class file is associated with the symbol in the properties/linkage panel (see Figure 4).

 

In the AS 2.0 class input field, enter the name of the class. If you have defined the class in a package, then put that path there as well.

com.iindwell.symbols.MySymbol

Now, when the MySymbol symbol is used, the MySymbol class is instantiated and associated with this symbol.

In the MySymbol class definition you will need to take a couple of preliminary steps before you can start using it. Look at the example class below:

class MySymbol extends MovieClip
static var symbolName:String = " MySymbol ";
static var symbolOwner:Object = MySymbol;
var className:String = " MySymbol ";
}

Flash requires that these three variables be defined in order to create a connection between the symbol and the class. The symbolName variable is pretty straightforward - it's the name of the symbol created in the properties panel for that movie clip. The symbolOwner variable is used internally with the createClassObject() method and should be a fully qualified package path (i.e., MySymbol or com.iindwell.MySymbol) depending on whether or not you defined the class in a package. The className variable is the name of the component class, and will be used with _global.styles as a reference name, i.e., _global.styles[className] (see help files for more info on styles).

Next, to access Flash UI Components, like the Button, TextField, or DateField components, in the class that I have defined and that's associated with the symbol that contains these components, I need to import the class that defines that component, then define a variable in my symbol class to represent that component that's named the same in that symbol. The variable name must be the same name as what I named the component in the properties panel (see Figure 5).

 

import mx.controls.Button;

class MySymbol extends MovieClip
static var symbolName:String = " MySymbol ";
static var symbolOwner:Object = MySymbol;
var className:String = " MySymbol ";
// add a variable definition for every component in your symbol to have a reference
in your code. Otherwise you will get a compile error if you reference
my_button without a definition.

//components
private var my_button:Button;

// constructor
function MySymbol() {
// an example of disabling the button component
my_button.enabled = false;
}
}

Event Handling
The last big step to get my development in Flash MX 2004 completed was to figure out how to handle events. In Flash MX, I used AsBroadcaster extensively to broadcast events and organize my listeners. However, ActionScript 2.0 functions differently. Instead of using the AsBroadcaster, use the EventDispatcher class. Using EventDispatcher is very simple if you're already familiar with AsBroadcaster. If you're not, that's okay; learning event handling with the EventDispatcher class is more flexible and better documented. Below is a class definition using EventDispatcher:

import mx.events.EventDispatcher;

class MyEventTestSymbol extends MovieClip {

static var symbolName:String = " MyEventTestSymbol ";
static var symbolOwner:Object = MyEventTestSymbol;
var className:String = " MyEventTestSymbol ";

// EventDispatcher Functions
/* these definitions will act as pointers to the functions in EventDispatcher
and are initialized in the EventDispatcher.initialize() method
that is called by the MyEventTestSymbol constructor.
*/

private var dispatchEvent:Function;
private var addEventListener:Function;
private var removeEventListener:Function;

function MyEventTestSymbol () {
EventDispatcher.initialize(this);

}
function testDispatch() {
// when this method is called, dispatchEvent method is fired raising an event
to it's listeners
dispatchEvent({type:"onMyEventTestSymbol Test", target:this});
}
}

The following is an example of another class listening in on MySymbol events:

class MainSymbol extends MovieClip {

static var symbolName:String = " MainSymbol ";
static var symbolOwner:Object = MainSymbol;
var className:String = " MainSymbol ";

// movie clips

private var mySymbol_mc:MovieClip; // this is the name given to an instance of
MySymbol on the stage

function onLoad() {
// add an event listener for the onMySymbolTest event, when
this event is fired, the local function onMySymbolTest will be called
mySymbol_mc.addEventListener("onMySymbolTest ", this);
// call the testDispatch method (this will fire the
onMySymbolTest event)
mySymbol _mc.testDispatch();
}

function onMySymbolTest () {
// at this point the onMySymbolTest event was fired from the mySymbol_mc
instance
trace("MySymbol distpatch test complete.");
}

}

Wrapping Up
Having figured out the core functionality of Flash MX 2004 and ActionScript 2.0, I am prepared to develop applications. The solid ground upon which you will develop your applications will be in understanding how and where to define your variables, classes, and methods. Understanding how to define your variables, classes, and methods and accessing them according to the scope they have been defined is at the root of your application. Having the ability to use advanced language features like inheritance and interfaces are tools that will make you more productive and strengthen the quality of your code. Finally, communicating between objects is essential. Learning how to develop event-driven applications will provide flexibility and power.

In this industry, technology is constantly changing. Fighting change will only stunt your career and job satisfaction. I admit this switch to ActionScript 2.0 has been a challenge, but I have also found it to be a lot of fun. Breaking existing patterns with new technology brings a renewed excitement and exploration. Fortunately, in this industry, if you ever feel the technology has become stale, a new release is always around the corner.

More Stories By Curtis Hermann

Curtis P. Hermann is a Macromedia Certified Flash MX Developer. He owns and operates a small consulting firm, iindwell, inc. (www.iindwell.com). He also heads the Flash MX development and quality-assurance department for WisdomTools.com (www.wisdom-tools.com).

Comments (0)

Share your thoughts on this story.

Add your comment
You must be signed in to add a comment. Sign-in | Register

In accordance with our Comment Policy, we encourage comments that are on topic, relevant and to-the-point. We will remove comments that include profanity, personal attacks, racial slurs, threats of violence, or other inappropriate material that violates our Terms and Conditions, and will block users who make repeated violations. We ask all readers to expect diversity of opinion and to treat one another with dignity and respect.


IoT & Smart Cities Stories
In his general session at 19th Cloud Expo, Manish Dixit, VP of Product and Engineering at Dice, discussed how Dice leverages data insights and tools to help both tech professionals and recruiters better understand how skills relate to each other and which skills are in high demand using interactive visualizations and salary indicator tools to maximize earning potential. Manish Dixit is VP of Product and Engineering at Dice. As the leader of the Product, Engineering and Data Sciences team at D...
Dynatrace is an application performance management software company with products for the information technology departments and digital business owners of medium and large businesses. Building the Future of Monitoring with Artificial Intelligence. Today we can collect lots and lots of performance data. We build beautiful dashboards and even have fancy query languages to access and transform the data. Still performance data is a secret language only a couple of people understand. The more busine...
Nicolas Fierro is CEO of MIMIR Blockchain Solutions. He is a programmer, technologist, and operations dev who has worked with Ethereum and blockchain since 2014. His knowledge in blockchain dates to when he performed dev ops services to the Ethereum Foundation as one the privileged few developers to work with the original core team in Switzerland.
René Bostic is the Technical VP of the IBM Cloud Unit in North America. Enjoying her career with IBM during the modern millennial technological era, she is an expert in cloud computing, DevOps and emerging cloud technologies such as Blockchain. Her strengths and core competencies include a proven record of accomplishments in consensus building at all levels to assess, plan, and implement enterprise and cloud computing solutions. René is a member of the Society of Women Engineers (SWE) and a m...
Andrew Keys is Co-Founder of ConsenSys Enterprise. He comes to ConsenSys Enterprise with capital markets, technology and entrepreneurial experience. Previously, he worked for UBS investment bank in equities analysis. Later, he was responsible for the creation and distribution of life settlement products to hedge funds and investment banks. After, he co-founded a revenue cycle management company where he learned about Bitcoin and eventually Ethereal. Andrew's role at ConsenSys Enterprise is a mul...
Whenever a new technology hits the high points of hype, everyone starts talking about it like it will solve all their business problems. Blockchain is one of those technologies. According to Gartner's latest report on the hype cycle of emerging technologies, blockchain has just passed the peak of their hype cycle curve. If you read the news articles about it, one would think it has taken over the technology world. No disruptive technology is without its challenges and potential impediments t...
If a machine can invent, does this mean the end of the patent system as we know it? The patent system, both in the US and Europe, allows companies to protect their inventions and helps foster innovation. However, Artificial Intelligence (AI) could be set to disrupt the patent system as we know it. This talk will examine how AI may change the patent landscape in the years to come. Furthermore, ways in which companies can best protect their AI related inventions will be examined from both a US and...
Bill Schmarzo, Tech Chair of "Big Data | Analytics" of upcoming CloudEXPO | DXWorldEXPO New York (November 12-13, 2018, New York City) today announced the outline and schedule of the track. "The track has been designed in experience/degree order," said Schmarzo. "So, that folks who attend the entire track can leave the conference with some of the skills necessary to get their work done when they get back to their offices. It actually ties back to some work that I'm doing at the University of San...
When talking IoT we often focus on the devices, the sensors, the hardware itself. The new smart appliances, the new smart or self-driving cars (which are amalgamations of many ‘things'). When we are looking at the world of IoT, we should take a step back, look at the big picture. What value are these devices providing. IoT is not about the devices, its about the data consumed and generated. The devices are tools, mechanisms, conduits. This paper discusses the considerations when dealing with the...
Bill Schmarzo, author of "Big Data: Understanding How Data Powers Big Business" and "Big Data MBA: Driving Business Strategies with Data Science," is responsible for setting the strategy and defining the Big Data service offerings and capabilities for EMC Global Services Big Data Practice. As the CTO for the Big Data Practice, he is responsible for working with organizations to help them identify where and how to start their big data journeys. He's written several white papers, is an avid blogge...