Accessibility

Flash ActionScript 2.0 Learning Guide

Macromedia

Instructional Media Development (IMD)
Macromedia Documentation

Editor: Jen deHaan

Flash Authoring QE
Adobe
Jen deHaan's blog
flashthusiast.com
webvideoblogger.com

Note: This learning guide introduces ActionScript in Flash and provides you with tools for developing your skills. The Flash product documentation is the source of many of these materials; always consult Flash Help or LiveDocs first when learning to use new features.

ActionScript is the scripting language used by Macromedia Flash. It makes your Flash content interactive. ActionScript provides a more efficient way to do things in Flash, from creating simple animations through designing complex, data-rich, interactive application interfaces. As the scripting language for Macromedia Flash, ActionScript has evolved incrementally over many releases. There are two versions of ActionScript: ActionScript 1.0 and ActionScript 2.0.

ActionScript 1.0, the less formal version of ActionScript, is fine for most general purposes and when you want to target an old version of Flash Player. Want to generate some simple interactivity when a user clicks a button? Want to create an application for a mobile device? Go with ActionScript 1.0. But for creating more complex code, ActionScript 2.0 is more appropriate.

ActionScript 2.0 is an object-oriented programming language that supports full class inheritance and all the features that developers demand from a mature language. It gives you a more flexible programming environment and superior debugging abilities. At the heart of ActionScript 2.0 is a formal and familiar approach to object-oriented programming (OOP), including full support for classes, inheritance, interfaces, and other common OOP concepts. ActionScript 2.0 also includes features that enhance ActionScript programming, such as variable data typing, function parameters and return types, and comprehensive debugging information. ActionScript 2.0 benefits developers by encouraging better programming structures and reducing coding and maintenance time. Want to write code using a formal programming language with more robust capabilities? Go with ActionScript 2.0.

To find out whether ActionScript 2.0 is right for your project or whether ActionScript 1.0 is the simpler, faster solution, check out the following resources, so you can make the call and be as efficient as possible for every project.

This guide introduces you to some of the fundamental concepts of ActionScript 2.0 and object-oriented programming. The following sections define common terminology, show you how to structure Flash applications, show you how to approach learning the ActionScript language and scripting in Flash, and where to go to find more information and examples.

Note: ActionScript coding conventions are very important for Flash designers and developers to ensure that code and applications are structured in a way that is intuitive and beneficial to themselves as well as other people working on the same project. For more information, see ActionScript 2.0 Best Practices.

If you're new to the ActionScript language, again, see the Syntax and Language Fundamentals section of the Learning ActionScript 2.0 manual in Flash LiveDocs for an introduction to ActionScript. If you're familiar with ActionScript and want to get started creating classes with ActionScript 2.0, see the “Writing Custom Classes” example in the Classes section of same manual.

Note: This learning guide if for Flash 8 users. Please see the previous version of the Flash ActionScript Learning Guide if you are using Flash MX 2004.

Requirements

To follow along with this learning guide, you will need to install the following software and files:

Macromedia Flash Basic 8

or Macromedia Flash Professional 8

Prerequisite Knowledge

A basic familiarity of Flash and a basic knowledge of the Flash workspace are required. Check out the Getting Started Learning Guide if you are using Flash for the first time.

About Script Assist

If you are uncomfortable writing ActionScript code or syntax, you might want to try using Script Assist mode in the Actions panel (Window > Actions). Script Assist is useful for creating scripts by making selections in the Actions panel and filling in text fields to automatically create statements in the Script pane. While you typically won’t use Script Assist for large applications, it is very useful for adding interactivity to your Flash applications, mocking up prototypes, and more.

Script Assist lets you build scripts by selecting items from the Actions toolbox, the list on the left side of the Actions panel. You can also select actions from the Add (+) pop-up menu. The Actions toolbox separates items into categories such as actions, properties, and objects, and also provides an index category that lists all items alphabetically. When you click an item once, its description appears at the upper right of the panel. When you double-click an item, it adds the item to the scrolling list on the right side of the panel in the Script pane.

In Script Assist mode, you can add, delete, or change the order of statements in the Script pane; you can also enter parameters for actions in text boxes above the Script pane. You can also use the standard Actions panel features while in Script Assist mode: you can find and replace text, view script line numbers, and pin a script—that is, keep a script in the Script pane when you click away from the object or frame.

To add an action to a Flash document, you must attach it to a button or movie clip, or to a frame in the Timeline. The Actions panel lets you select, drag and drop, rearrange, and delete actions.

To write ActionScript using Script Assist:

  1. Select Window > Actions.
    The Actions panel appears.
  2. Click the Script Assist button,
    The Actions panel enters Script Assist mode.

Note: If the Actions panel contains ActionScript code when you click the Script Assist button, Flash validates the existing code. If there are errors in the code, you will not be able to use Script Assist until you fix (or comment out) the current code selection. For information on removing and manipulating scripts, see the following section of Flash LiveDocs: Using Flash > Writing ActionScript with Script Assist > Using Script Assist to Write ActionScript.

When Script Assist is enabled, the Actions panel user interface and behaviors change in the following ways:

For more information on adding, removing, and manipulating scripts using Script assist, see the following section of Flash LiveDocs: Using Flash > Writing ActionScript with Script Assist > Using Script Assist to Write ActionScript.

The Flash documentation (both in Flash Help and in LiveDocs) contains hands-on examples that show you how to use Script Assist. For an example of writing a script using Script Assist, see Using Flash > Writing ActionScript with Script Assist > Creating a startDrag/stopDrag Event Using Script Assist. For a tutorial that shows you how to build a small application using Script Assist, see Flash Tutorials > ActionScript: Use Script Assist Mode.

ActionScript 2.0 Language Details

ActionScript 2.0 introduces several programming keywords and concepts, including classes, inheritance, and interfaces. These concepts comprise what is commonly known as object-oriented programming. See the following sections of Flash LiveDocs for more information:

Features of ActionScript 2.0 include the following:

When you use ActionScript 2.0, make sure that the publish settings for the FLA file specify ActionScript 2.0. This is the default for files created in Flash 8. However, if you open an older FLA file that uses ActionScript 1.0 and begin rewriting it in ActionScript 2.0, change the publish settings of the FLA file to ActionScript 2.0. If you don't, your FLA file will not compile correctly, and no errors will be generated.

Classes you create in ActionScript must be stored in separate ActionScript (AS) files; you can't create classes in a frame on a timeline (frame script), or attach one to a movie clip or button instance. Some important points about class files:

For more information on classes and object-oriented programming, read the Object-Oriented Programming section of this guide. If you're new to creating classes and object-oriented programming, try the steps in the following section of Flash LiveDocs: Learning ActionScript 2.0 > Classes > Example: Writing Custom Classes.

For more information, see the following sections of Flash LiveDocs:

Choosing Between ActionScript 1.0 and ActionScript 2.0

When you start a new document or application in Flash, you must decide how to organize its associated files. You might use classes in some projects, such as when you are building complex applications, but not all documents use classes. For example, many short examples in the Flash documentation do not use classes.

Using classes to store functionality is not the easiest or best solution for small applications or simple FLA files. When you build a small project, it is often more work and effort to use classes or external code files to organize ActionScript instead of adding ActionScript within the FLA file. It is often more efficient to put ActionScript inside the document. In this case, try to put all your code on the Timeline on as few frames as possible, and avoid placing code on or in instances (such as buttons or movie clips) in a FLA file.

If you decide to keep all the ActionScript code within the FLA file, rather than placing it within a class that you import, this does not mean that you should necessarily use ActionScript 1.0. You might decide to put your code inside the FLA document and still opt to use ActionScript 2.0 with its strict data typing and its new methods and properties. ActionScript 2.0 also offers a syntax that follows standards in other programming languages. This makes the language easier and more valuable to learn. For example, you will feel familiar with ActionScript if you have encountered another language that's based on the same structure and syntax standards. Or, you can apply this knowledge to other languages you learn in the future. ActionScript 2.0 lets you use an object-oriented approach to developing applications by using an additional set of language elements, which can be advantageous to your application development.

In some cases, you cannot choose which version of ActionScript to use. If you are building a SWF file that targets an old version of Flash Player, such as a mobile device application, you must use ActionScript 1.0, which is compatible with Flash Player for a number of devices.

Remember, regardless of the version of ActionScript, you should follow good practices. Many of these practices, such as remaining consistent with case sensitivity, using code completion, enhancing readability, avoiding keywords for instance names, and keeping a consistent naming convention, apply to both versions. If you plan to update your application in future versions of Flash, or make it larger and more complex, you should use ActionScript 2.0, classes, and version control, to make it easier to update and modify your application. For more information on class files, see the Object-Oriented Programming section.

Migrating to ActionScript 2.0

The first thing to understand about updating ActionScript 1.0 code to ActionScript 2.0 code is that, in many cases, it's not necessary. ActionScript you wrote in earlier versions of Flash continues to work in Flash 8 and Flash Player 8.

Migrating your code from ActionScript 1.0 to ActionScript 2.0 is beneficial mainly in the following circumstances:

Also remember that you do not need to write class files in order to leverage some of the benefits or capabilities of ActionScript 2.0 or V2 components. You can still write ActionScript 2.0 code (such as code that applies data type annotations to variables) using frame scripts on a timeline.

Understanding ActionScript and Flash Player

Although new versions of ActionScript and Flash Player are often released simultaneously, they are not always synonymous. There are distinctions between Flash Player and ActionScript versions that can be very important to understand when building Flash applications.

You can compile a Flash document using ActionScript 1.0 or ActionScript 2.0 to Flash Player 6, 7, or 8, and it will work correctly. That is because both ActionScript 1.0 and ActionScript 2.0 compile to the same bytecode (the code that the ActionScript interpreter in Flash Player reads.) However, there are new ActionScript APIs (functions, classes, properties, and methods) introduced in each new version of Flash Player. For example, the loadMovie() method of the MovieClip class works in Flash Player 6, 7, and 8. However, the MovieClipLoader class works only in Flash Player 7 and 8. That means that even though you can use either ActionScript 1.0 or ActionScript 2.0 for any of those player versions, you have to be careful that the APIs you use are supported in the target player version.

Neither ActionScript 1.0 nor ActionScript 2.0 are case-sensitive. However, Flash Player 7 and Flash Player 8 are case-sensitive. That means that regardless of whether or not you use ActionScript 1.0 or 2.0 the variables userName and UserName are the same in Flash Player 6, but they are different variables in Flash Players 7 and 8.

Understanding Data

Data refers to the numbers, strings, and other information that you can manipulate within Flash. Using data is usually essential when you create applications or websites. You also use data when you create advanced graphics and script-generated animation, and you might have to manipulate values that you use to drive your effects.

You can define data in variables within Flash, or you can load data from external files or sites using XML, web services, and so on. You can store data in a database and then represent that information in several ways in a SWF file. This can include displaying the information in text fields or components or displaying images in movie clip instances.

Some of the most common kinds of data include strings (a sequence of characters, such as names and passages of text), numbers, objects (such as movie clips), Boolean values (true and false).

Data Types

A data type describes a piece of data and the kinds of operations that you can perform on it. You store data in a variable (see the Variables section) below. You use data types when creating variables, object instances, and function definitions to assign the type of data you're working with. You use many different data types when you write ActionScript.

You can classify different types of data using a data type to assess how you can use the data. For example, you can perform mathematical operations with number data, but you cannot meaningfully rotate a number. A movie clip, on the other hand, can be rotated, but you cannot meaningfully multiply a movie clip by another movie clip.

ActionScript 2.0 enables you to formally specify the data type for variables, parameters, and function return types, and tell Flash what classification of data can be used in that context. For example, if you declare a variable as a String data type then you can assign only strings to that variable. If you attempt to assign a number to the variable Flash will throw a compiler error.

ActionScript has two basic classifications for data types: primitive and complex.

Variables that contain primitive data types behave differently in certain situations than those containing complex types. For more information, see the following Flash LiveDocs sections:

All data types and classes are fully defined in the “ActionScript 2.0 Language Reference” in Flash LiveDocs.

Variables

A variable is a container that holds information. The following ActionScript shows what a variable looks like in ActionScript:

var myVariable:Number = 10;

This variable holds a numerical value. The use of :Number in the previous code assigns the type of value that variable holds, called data typing. For more information on data typing, see Assigning Data Types below.

The container (represented by the variable name) is always the same throughout your ActionScript, but the contents (the value) can change. You can change the value of a variable in a script as many times as you want. When you change the value of a variable while the SWF file plays, you can record and save information about what the user has done, record values that change as the SWF file plays, or evaluate whether a condition is true or false. You might need the variable to continually update while the SWF file plays, such as when a player's score changes in a Flash game. Variables are essential when you create and handle user interaction in a SWF file.

Variables can hold different types of data; for more information, see About Data Types in LiveDocs (Learning AS 2.0 > Data and Data Types > About Data Types). The type of data that a variable contains affects how the variable's value changes when you assign that value in a script.

Typical types of information that you can store in a variable include a URL (String type), a user's name (String type), the result of a mathematical operation (Number type), the number of times an event occurred (Number type), or whether a user has clicked a particular button (Boolean type). Each SWF file and object instance (such as a movie clip) has a set of variables, with each variable having a value independent of variables in other SWF files or movie clips.

To view the value of a variable, use the trace() statement to send the value to the Output panel. Then, the value appears in the Output panel when you test the SWF file in the test environment. For example, trace(hoursWorked) sends the value of the variable hoursWorked to the Output panel in the test environment. You can also check and set the variable values in the Debugger in the test environment.

For more information on variables, see the following topics in the About Variables section of Learning ActionScript 2.0 volume of the Flash documentation (available in Flash Help and in Flash LiveDocs at Learning ActionScript 2.0 > Data and Data Types > About Variables):

Assigning Data Types:

You can explicitly declare the object type of a variable when you create the variable, which is called strict data typing. If you do not explicitly define an item as holding either a number, a string, or another data type, Flash Player tries to determine the data type of an item when it is assigned (at runtime). For information on strict data typing, and examples, see the following topics in the About Data Types section of Learning ActionScript 2.0 volume of the Flash documentation (available in Flash Help and in Flash LiveDocs at Learning ActionScript 2.0 > Data and Data Types > About Data Types):

About Syntax and Statements

Learning ActionScript syntax and statements is like learning how to put together words to make sentences, which you can then put together into paragraphs. ActionScript can be just as simple. For example, in English, a period ends a sentence; in ActionScript, a semicolon ends a statement. In the ActionScript language, you can type a stop() action to stop the playhead of a movie clip instance or a SWF file from looping. Or you can write thousands of lines of code to power an interactive banking application. As you can see, ActionScript can do very simple or very complex things.

In the Understanding Data section, you learned how the ActionScript language uses data, and how you can format syntax. This section demonstrates how you can form statements in ActionScript using syntax. It contains many short code snippets and some examples to demonstrate fundamental language concepts. Upcoming sections contain longer and increasingly involved code examples that combine and facilitate the fundamentals you learn in this chapter.

The general rules described in this section apply to all ActionScript. Most ActionScript terms also have individual requirements; for the rules for a specific term, see the Terminology section of Learning ActionScript 2.0 in the Flash LiveDocs, or see its individual entry in the ActionScript 2.0 Language Reference. (The ActionScript 2.0 Language Reference, contain in the Flash documentation, is the central reference or dictionary for developers using ActionScript.) Applying the basics of ActionScript in a way that creates elegant programs can be a challenge for users who are new to ActionScript. For more information on how to apply the rules described in this section, see Coding Conventions for ActionScript 2.0 (Learning ActionScript 2.0 > Best Practices and Coding Conventions for ActionScript 2.0).

Looking at Language Elements

The ActionScript language is made up of the built-in classes that make up the ActionScript language. You need to use correct ActionScript syntax to form statements so the code compiles and runs correctly in Flash. In this case, syntax refers to the grammar and spelling of a language that you program with. The compiler cannot understand incorrect syntax, so you see errors or warnings displayed in the Output panel when you try to test the document in the test environment. Therefore, syntax is a collection of rules and guidelines that help you form ActionScript correctly.

A statement is an instruction you give the FLA file to do something, such as to perform a particular action. For example, you can use a conditional statement to determine whether something is true or exists. Then you might execute actions that you specify, such as functions or expressions, based on whether the condition is true or not. The if statement is a conditional statement and evaluates a condition to determine the next action that should occur in your code.

// if statement
if (condition) {
  // statements;
}

Expressions, different from statements, are any legal combination of ActionScript symbols that represent a value. Expressions have values, while values and properties have types. An expression can consist of operators and operands, values, functions, and procedures. The expression follows ActionScript rules of precedence and of association. Typically, Flash Player interprets the expression and then returns a value that you can use in your application. For example, the following code is an expression:

x + 2

In the previous expression, x and 2 are operands and + is an operator. For more information on operators and operands, see the following section of Flash LiveDocs: Learning ActionScript 2.0 > Syntax and Language Fundamentals > About Operators in the Flash documentation. For more information on objects and properties, see the following section of Flash LiveDocs: Learning AS 2.0 > Data and Data Types > About Data Types > About Primitive and Complex Data Types > Object Data Type.

The way you format your ActionScript also determines how maintainable your code is. For example, it's difficult to read the logic of a FLA file that doesn't contain indents or comments, or contains inconsistent formatting and naming conventions. When you indent blocks of ActionScript (such as loops and if statements), the code is easier to read and debug if you encounter problems. For more information about formatting ActionScript, see the following section of Flash LiveDocs: Learning ActionScript 2.0 > Best Practices and Coding Conventions for AS 2.0 > Formatting ActionScript Syntax.

In ActionScript, you use a dot (.) operator (dot syntax) to access properties or methods that belong to an object or instance on the Stage. You also use the dot operator to identify the target path to an instance (such as a movie clip), variable, function, or object. A dot syntax expression begins with the name of the object or movie clip, followed by a dot, and it ends with the element you want to specify. The following sections demonstrate how to write dot syntax expressions.

To control a movie clip, loaded movie, or button, you must specify a target path. Target paths are hierarchical addresses of movie clip instance names, variables, and objects in a SWF file. To specify a target path for a movie clip or button, you must assign an instance name to the movie clip or button. You name a movie clip instance by selecting the instance and typing the instance name in the Property inspector. Or you can specify the instance name with code if you create the instance using ActionScript. You can use the target path to assign an action to a movie clip or to get or set the value of a variable or property.

For more information on assigning an instance name and using dot syntax to target an instance, see the following section of Flash LiveDocs: About Using Dot Syntax to Target an Instance (Learning ActionScript 2.0 > Syntax and Language Fundamentals > About Dot Syntax and Target Paths > About Using Dot Syntax to Target an Instance) and About Scope and Targeting (Learning ActionScript 2.0 > Syntax and Language Fundamentals > About Dot Syntax and Target Paths > About Scope and Targeting).

Note: When you write ActionScript for Flash Player 7 and later, your code is case-sensitive. This means that variables with slightly different capitalization are considered different from each other.

Punctuators are the characters that help form your ActionScript code. There are several language punctuators in Flash. The most common type of punctuators are semicolons (;), colons (:), parentheses [()] and braces ({}). Each of these punctuators has a special meaning in the ActionScript language and helps define data types, terminate statements or structure ActionScript. For more information, see About Language Punctuators (Learning ActionScript 2.0 > Syntax and Language Fundamentals > About Language Punctuators).

Constants are properties with a fixed value that cannot be altered, so they are values that don't change throughout an application. Flash includes several predefined constants, which can help simplify application development. An example of constants can be found in the Key class, which includes many properties, such as Key.ENTER or Key.PGDN. If you rely on constants, you never have to remember that the key code values for the Enter and Page Down keys are 13 and 34. Using constant values not only makes development and debugging easier, but it also makes your code easier to read by your fellow developers. For more information, see the following section of Flash LiveDocs: Using Constants (Learning ActionScript 2.0 > Syntax and Language Fundamentals > About Constants and Keywords > Using Constants).

Keywords in ActionScript are used to perform specific kinds of actions. They are also reserved words because of this, so you can't use them as identifiers (such as variable, function, or label names). Examples of some reserved keywords are if, else, this, function, and return. For more information, see the following section of Flash LiveDocs: About Keywords (Learning ActionScript 2.0 > Syntax and Language Fundamentals > About Constants and Keywords > About Keywords).

An array is an object whose properties are identified by numbers representing their positions in the structure. Essentially, an array is a list of items. Unlike some languages, ActionScript does not require that each element in an array is of the same data type. You can mix numbers, dates, strings, and objects and even add a nested array at each array index. For more information, see the following section of Flash LiveDocs: About Arrays (Learning ActionScript 2.0 > Syntax and Language Fundamentals > About Arrays).

Operators are characters that specify how to combine, compare, or change values in an expression. An expression is any statement that Flash can evaluate and that returns a value. You can create an expression by combining operators and values or by calling a function. For more information on expressions, see the following section of Flash LiveDocs: About Syntax, Statements, and Expressions (Learning ActionScript 2.0 > Syntax and Language Fundamentals > About Syntax, Statements, and Expressions).

For example, a mathematical expression uses numerical operators to manipulate the values you use. Examples of operator characters are +, <, *, and =. An expression consists of operators and operands, and they are any legal combination of ActionScript symbols that represent a value. An operand is the part of your code that the operator performs actions on. For example, in the expression x + 2, x and 2 are operands and + is an operator. For more information on operators, see the following section of Flash LiveDocs: About Operators (Learning AS 2.0 > Syntax and Language Fundamentals > About Operators).

For information on syntax and statements, see the following sections in the Flash LiveDocs:

Handling Events

Events are actions that occur while a SWF file is playing. An event such as a mouse click or a keypress is called a user event because it occurs as a result of direct user interaction. An event that Flash Player generates automatically, such as the initial appearance of a movie clip on the Stage, is called a system event because it isn't generated directly by the user.

For your application to react to events, you must use event handlers—ActionScript code associated with a particular object and event. For example, when a user clicks a button on the Stage, you might advance the playhead to the next frame. Or when an XML file finishes loading over the network, the contents of that file might appear in a text field.

You can handle events in ActionScript in different ways depending on the type of event. The following lists each of the ways to handle events in ActionScript. Not all of the following apply to all event types.

Using button and movie clip event handlers is not recommend, because they require that you attach code to objects. Instead, the best practice is to place code in frame scripts on the Timeline, or in a class file using event handler methods whenever possible.

Note: Using event handlers with the MovieClip.loadMovie method can be unpredictable. If you attach an event handler to a button using on(), or if you create a dynamic handler using an event handler method such as the MovieClip.onPress handler, and then you call loadMovie(), the event handler is not available after the new content is loaded. However, if you use the onClipEvent handler or the on handler to attach an event handler to a movie clip, and then call loadMovie() on that movie clip, the event handler is still available after the new content is loaded.

Event Handler Methods

An event handler method is a method of a class that is invoked when an event occurs on an instance of that class. For example, the MovieClip class defines an onPress event handler that is invoked whenever the mouse is pressed on a movie clip object. Unlike other methods of a class, however, you don't invoke an event handler directly; Flash Player invokes it automatically when the appropriate event occurs.

The following ActionScript classes are examples of classes that define event handlers: Button, ContextMenu, ContextMenuItem, Key, LoadVars, LocalConnection, Mouse, MovieClip, MovieClipLoader, Selection, SharedObject, Sound, Stage, TextField, XML and XMLSocket. For more information about the event handlers they provide, see the entries for each class in ActionScript 2.0 Language Reference. Note that the word handler is added in the title of each event handler.

By default, event handler methods are undefined: when a particular event occurs, its corresponding event handler is invoked, but your application doesn't respond further to the event. To have your application respond to the event, you define a function with the function statement and then assign that function to the appropriate event handler. The function you assign to the event handler is then automatically invoked whenever the event occurs.

An event handler consists of three parts: the object to which the event applies the name of the object's event handler method, the function you assign to the event handler, and your code. The following example shows the basic structure of an event handler:

object.eventMethod = function ():Void {
    // Your code here, responding to event.
};

For example, suppose you have a button named next_btn on the Stage. The following code assigns a function to the button's onPress event handler; this function advances the playhead to the next frame in the current timeline:

next_btn.onPress = function ():Void {
    nextFrame();
};

You can assign a function reference, receive passed parameters to the event handler, assign functions to event handlers, and override methods. For more information on these topics, see the following section of Flash LiveDocs: Using Event Handler Methods (Learning ActionScript 2.0 > Handling Events > Using Event Handler Methods).

Event Listeners

Event listeners let an object, called a listener object, receive events broadcast by another object, called a broadcaster object. The broadcaster object registers the listener object to receive events generated by the broadcaster. For example, you can register a movie clip object to receive onResize notifications from the Stage, or a button instance could receive onChanged notifications from a text field object. You can register multiple listener objects to receive events from a single broadcaster, and you can register a single listener object to receive events from multiple broadcasters.

The listener-broadcaster model for events, unlike event handler methods, lets you have multiple pieces of code listen to the same event without conflict. Event models that do not use the listener/broadcaster model, such as XML.onLoad(), can be problematic when various pieces of code are listening to the same event; the different pieces of code have conflicts over control of that single XML.onLoad callback function reference. With the listener/broadcaster model, you can easily add listeners to the same event without worrying about code bottlenecks.

Note: The following ActionScript classes can broadcast events: Key, Mouse, MovieClipLoader, Selection, Stage, and TextField. To see which listeners are available for a class, see each class entry in the Flash LiveDocs ActionScript 2.0 Language Reference volume.

Event Listener Model

The event model for event listeners is similar to the model for event handlers (see Using event handler methods), with two main differences:

The following code outlines the event listener model:

var listenerObject:Object = new Object();
listenerObject.eventName = function(eventObj:Object):Void {
    // Your code here
};
broadcasterObject.addListener(listenerObject);

The code starts with an object, listenerObject, with a property eventName. Your listener object can be any object, such as an existing object, movie clip, or button instance on the Stage, or it can be an instance of any ActionScript class. For example, a custom movie clip could implement the listener methods for Stage listeners. You could even have one object that listens to several types of listeners.

The eventName property is an event that occurs on broadcasterObject, which then broadcasts the event to listenerObject. You can register multiple listeners to one event broadcaster.

You assign a function to the event listener that responds to the event in some way.

Last, you call the addListener() method on the broadcaster object, passing the listener object to the addListener() method.

To unregister a listener object from receiving events, you call the removeEventListener() method of the broadcaster object, passing it the name of the event to remove, and the listener object.

broadcasterObject.removeListener(listenerObject);

For an example of using an event listener, see the following section of Flash LiveDocs Using Event Listeners (Learning ActionScript 2.0 > Handling Events > Using Event Listeners).

For more information on handling events, see the following sections of Flash LiveDocs in the Handling Events section of Learning ActionScript 2.0:

Object-Oriented Programming

ActionScript 2.0 is fully object-oriented programming (OOP) language that provides several benefits to programmers, especially when creating large-scale Flash applications or presentations. OOP encourages reusability. You reuse a class you created in ActionScript 2.0 by inheriting the functionality of that class in other classes. The modular nature of OOP lets you replace or swap components of an application without changing the application's structure. Finally, the fundamental metaphors of OOP design closely mirror the natural world (objects that have internal states and can do certain things), which speeds and facilitates the application design process.

Like ActionScript, OOP languages are based on the concept of classes and instances. A class defines all of the properties that distinguish a series of objects—it defines a category of object. A class describes the properties (data) and methods (behaviors) for an object, much like an architectural blueprint describes the characteristics of a building. The Date class is an intrinsic ActionScript class. Using the Date class you can make many instances. Each instance, or Date object, can represent a different (or the same) date. For example, you can make a Date object to represent August 1, 2010 and another to represent August 2, 2010. Each object inherits the same functionality from the Date class. However, each instance is an independent object much as two buildings built from the same blueprint are unique instances.

Classes define data types. (see the Understanding Data Types section) When an application has a new logical classification for data that doesn't fit any pre-existing data types, you can write a new class. For example, if you are building an application that showcases t-shirts then you can write a TShirt class that defines the characteristics of that data type such as color and style. To define a class, you use the class keyword in an external script file. You can create an external script file in the Flash authoring tool by selecting File > New > ActionScript File.

As always, ActionScript 2.0 provides several powerful and familiar OOP concepts and keywords (such as class, interface, and package) found in other programming languages, such as Java. The programming language lets you build program structures that are reusable, scalable, robust, and maintainable. It can also decrease development time by providing users with thorough coding assistance and debugging information. You can use ActionScript 2.0 to create objects and establish inheritance, and to create custom classes and extend the top-level and built-in classes in Flash.

Flash Basic 8 and Flash Professional 8 include approximately 65 top-level classes that provide everything from core data types (Array, Boolean, Date, and so on), to custom errors and events, as well as several ways to load external content (XML, images, variables, and more). You can also write your own custom classes and integrate them into your Flash documents, or extend the top-level classes and add your own functionality or modify existing functionality. For an example, see the tutorial in the following section of Flash LiveDocs: Learning ActionScript 2.0 > Classes > About Working with Custom Classes in an Application > About Class Members, that shows you how to make a custom Person class, which contains custom properties for the person's name and age. You can then treat this custom class as a new data type in your documents and create a new instance of the class using the new operator.

You write a custom class in an external ActionScript (AS) file and you can import it into your application when you compile the FLA file. Classes can be very useful when you build larger Flash applications because you can organize a lot of the application's complexity in external class files. When you move a lot of the logic into a custom class, you can not only make the code easier to reuse, but you can also “hide” some of the methods and properties from other parts of the ActionScript code. This helps you prevent other developers on the team from accessing sensitive information, or changing data that shouldn't be changed.

When you use a class, you can also extend existing classes and add new functionality or modify existing functionality. For example, if you create three very similar classes, you can write a base class (abstract) and then write three classes (implementations) that extend the base class. These three subclasses can add additional methods and properties, so that you don't need to create three class files that all duplicate the same code and logic.

Another benefit of using classes is code reusability. For example, if you create a custom class that creates a custom progress bar using the Drawing API, you could save the progress bar class in your classpath and reuse the same code in all of your Flash documents by importing the custom class. For more information on setting the classpath, see About Importing Class Files and About Setting and Modifying the classpath.

For a general introduction to the principles of OOP, see the following section of Flash LiveDocs: Object-Oriented Programming Fundamentals (Learning ActionScript 2.0 > Classes > About Object-Oriented Programming and Flash > Object-Oriented Programming Fundamentals).

For more information on OOP and writing custom class files, see the following topics in the Classes chapter of Learning ActionScript 2.0 in the Flash LiveDocs:

Where to Go from Here

The following books and resources can help you learn about more advanced ActionScript topics and object-oriented programming.

Developer Center articles:

Book excerpts:

Recommended books:

The following resources were produced for Flash MX 2004, but many sections are still applicable to Flash 8:

About the authors

Macromedia Instructional Media Development (IMD) is a team of instructional designers, developers, technical writers, technical editors, publishing engineers, and multimedia artists. IMD authors the online help systems, manuals, tutorials, and examples that help customers learn how to use Macromedia products.
Jen deHaan, a rather awkward and uncool Canadian, likes robots and pirates (as well as robotic pirates). Jen works on documentation at Macromedia in San Francisco. She also maintains a blog at weblogs.macromedia.com/dehaan and believes that _root and low-carb diets are unusually evil.