BUY THIS BOOK
Add to Cart

Print Book $39.99


Add to Cart

PDF $31.99

Safari Books Online

What is this?

Add to UK Cart

Print Book £24.99

What is this?

Looking to Reprint or License this content?


Learning ActionScript 3.0
Learning ActionScript 3.0 The Non-Programmer's Guide to ActionScript 3.0

By Rich Shupe, Zevan Rosser
Book Price: $39.99 USD
£24.99 GBP
PDF Price: $31.99

Cover | Table of Contents


Table of Contents

Chapter 1: ACTIONSCRIPT OVERVIEW
While you likely know what ActionScript is and are eager to begin working with the new version, a brief overview of its development will give you some insight into its use—particularly related to Flash Player and how it handles different versions of ActionScript. This brief introductory chapter will give you a quick look at where ActionScript 3.0 fits into your workflow, and will cover:
  • What Is ActionScript 3.0? It's to be expected that a new version of ActionScript will bring with it new features. However, this version has been written anew from the ground up and is even handled separately from previous versions of ActionScript at runtime. This intentional splintering of Flash Player affords significant performance increases, but also brings with it limitations as to how multiple versions of ActionScript interact.
  • The Flash Platform. At the time of this writing, ActionScript 3.0 is the internal programming language of Flex and AIR (the Adobe Integrated Runtime application). Differences in compiling and environment-specific attributes prevent every file written in ActionScript 3.0 from working in every aspect of the Flash Platform, but the fundamentals—indeed the bulk—of the language is the same throughout.
  • Procedural Versus Object-Oriented Programming. A great deal of attention has been focused on the object-oriented programming (OOP) capabilities of ActionScript 3.0, and the power and robustness of the language really shine in this area. However, you'll be happy to learn that a move to ActionScript 3.0 doesn't mean that you must become an expert at OOP. It is still possible to use a structured collection of functions, which characterize procedural programming, to author ActionScript 3.0 projects. In addition, using Flash CS3, it is still possible to code in the timeline, rather than coding exclusively with external classes. If you prefer object-oriented programming, enhancements to ActionScript 3.0's OOP infrastructure make it more robust and bring it more in line with the features of other important, OOP-based languages (such as Java) and make moving between such languages a bit easier.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
What Is ActionScript 3.0?
Although the new version of Flash's internal scripting language contains much that will be familiar to users of prior versions, it's probably best to think of ActionScript 3.0 as entirely new, for a few simple reasons. First, a few things are quite different, such as the event model and the way assets are displayed. Second, subtle changes run throughout the language and require some attention until they become second nature. These are usually small concerns, such as a slight change in the name of a property.
Most importantly, however, ActionScript 3.0 has been rewritten from the ground up and uses a different code base than prior versions of the language. This optimization provides relatively dramatic performance increases, but it means that ActionScript 3.0 code cannot be mixed with prior versions of the language in the same file.
The newness of this version, however, shouldn't intimidate you. It's true that the learning curve for ActionScript 3.0 is steeper than for prior versions, but that is usually a function of its robustness more than one of difficulty. Typically, there is an adjustment period during which users must occasionally adapt to a slightly new way of doing things.
To help you get over any possible trepidation, here's a look at some of the highlights of the new features of ActionScript 3.0. Keeping these benefits in mind may help make it easier to accept change, particularly when that change may initially seem tedious or overly complicated. Select new features include:
More detailed error reporting
ActionScript 3.0 requires strict data typing of variables, arguments, function returns, and so on. This data typing is discussed in , but boils down to telling the compiler what kind of data you expect to be working with at any specific time. Data type checking was introduced in ActionScript 2.0 but was previously optional. The heightened data typing enforcement improves error checking and provides more information while coding to allow you to correct the problem. Further, ActionScript 3.0 now enforces static data typing at runtime. This improves data type reliability at runtime, and also improves performance and reduces memory usage because the data types are stored in machine code rather than having to be dynamically addressed at runtime.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
The Flash Platform
It's important to note that this book focuses primarily on developing ActionScript 3.0 applications using the Flash CS3 Professional integrated development environment (IDE). However, ActionScript 3.0 is the programming language for other Flash Platform applications, as well—notably Flex and AIR (the Adobe Integrated Runtime desktop delivery application).
AIR projects can also include HTML, JavaScript, and PDF, but ActionScript 3.0 is a large part of its appeal and the language most relevant to this discussion.
This means that the scripting skills you develop in Flash CS3 will be largely applicable in other areas of the Flash Platform, extending your reach as a programmer. There are, however, some important differences to understand when examining the big picture of cross-application scripting. We'll give you just a few brief examples here to consider.
To start with, Flash and Flex have different compilers so there is no guarantee that your project will compile correctly in both applications. You can use Flex Builder (the Flex compiler) to compile code-only ActionScript SWFs without the Flex framework, and load them into Flash CS3-generated projects. You can also load Flash CS3-compiled SWFs into a Flex project. However, as soon as you depart from core language needs, things start to get sticky.
For example, Flex does not have the resources of the Flash IDE to create visual assets (such as movie clips) and, by the same token, Flash does not support the Embed tag used by Flex to include such assets. This means that the same code cannot always be used seamlessly when such custom visuals are required. Similarly, the component architecture is different, including a different format and a component set that do not match.
This issue with visual assets has been a hotly debated issue for a while, and progress is being made to smooth the waters a bit. Adobe released a patch for Flex 2, and Flex 3 is in public testing at the time of this writing, improving the compatibility of components. However, it will probably be a while before moving code to and from these applications will be a comfortable process, if it ever happens. At a brisker pace, however, AIR development is becoming more of a crossover affair. Adobe is continuing to work on AIR authoring workflows that originate in Flash CS3.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Procedural Versus Object-Oriented Programming
Much discussion has been made over the pros and cons of procedural versus object-oriented programming. To touch briefly on this, here is a little background concerning the evolution of ActionScript. ActionScript started as a sequential programming language, meaning that scripting was limited to a linear sequence of instructions telling Flash what to do in a step-by-step manner. This approach to scripting was not terribly flexible and did not promote reuse.
As the language evolved, it became a procedural programming language. Like sequential programming, procedural programming relied on a step-by-step set of instructions but introduced a more structured, modular approach to scripting. Procedures, otherwise known as functions (or, sometimes, subroutines), could be executed again and again as needed from different parts of a project, without copying and pasting copies of the code into the ongoing sequence of instructions. This modularity promoted reuse, and made the code easier to edit and more efficient.
Scripters in search of an even greater degree of modularity and reuse gravitated toward object-oriented programming. OOP languages create programs that are a collection of objects. Objects are individual instances of classes—collections of code that are self-contained and do not materially alter or disrupt each other. Dividing code into small capsules, appropriately known as encapsulation, is one of the hallmarks of an OOP language. Another important feature of OOP is inheritance, or the ability to derive classes from parent classes, passing on specific characteristics from the parent.
A classic example of OOP structure, and specifically inheritance, defines a set of transportation vehicles. You might start with a generic Vehicle class that includes traits common to all vehicles, such as the basic physics of movement. You might then create three subclasses: GroundVehicle, WaterVehicle, and AirVehicle. These classes would alter or introduce traits specific to ground, water, and air travel, respectively, but not yet be complete enough to represent an actual vehicle. Further derived classes might be
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
The Document Class
If you decide you would like to start thinking in OOP terms right away, we will show you how to easily take a step in that direction. Flash CS3 introduced a new feature that simplifies associating a main class, or application entry point with your FLA. It is called the document class and it does all the work of instantiating the class for you. This means you don't need any code in the timeline at all, and can edit all examples in Flash or the external text editor or development environment of your choice.
If you don't plan to start using OOP until we roll it out in later chapters, feel free to skip this section as it will be repeated in . We will provide minimal explanation here just to get you going using the document class, and will explain this material in greater detail in later chapters throughout the book.
Let's start with a simulated chapter example that you might use in the timeline. It does nothing more than use the trace() method to place a word into the fOutput panel—an authoring-only panel that accepts text output from your file.
trace("Flash");
To create a document class, you're going to create a kind of wrapper that encloses the trace() method in the correct class syntax.
Create a new ActionScript file (rather than a new FLA document) and type the following document class shell:
1   package {
2
3      import flash.display.MovieClip;
4
5      public class Main extends MovieClip {
6
7          public function Main() {
8
9          }
10
11      }
12  }
The first line, along with the closing brace in line 12, defines the class's package. A package is a mandatory structure that ensures your class is known to the compiler. Next, you must import any classes that you need to use in your package.
A document class essentially serves as a shortcut for creating an instance of a movie clip or sprite (a new Flash object that is nothing more than a one-frame movie clip) and adding it to the display list so it can be displayed by Flash Player. (This is true even when there is nothing to display, as in this case. We will cover manipulating the display list in .)
All document classes must be derived from either the
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Legacy Code Compatibility
I'd like to end this chapter with a small caveat. You cannot mix ActionScript 1.0 or 2.0 code with ActionScript 3.0 code in the same SWF. You are unlikely to do this if you're learning from scratch, but you may run into this situation if you attempt to update legacy projects by adding ActionScript 3.0 code.
If you ever have the need to run a discrete mixture of ActionScript 3.0 and a prior version of the language, such as showing a legacy file within a new demo interface shell, you can do so by loading a SWF. An ActionScript 3.0 file can load a SWF created in ActionScript 1.0 or 2.0, but it cannot access the older SWF's variables or functions. For all intents and purposes, the same is not true in reverse. An older SWF cannot load an ActionScript 3.0 SWF.
In , we will discuss how to communicate between these two discrete SWFs using a special process. For now, however, just remind yourself again that you cannot combine ActionScript 3.0 with older versions of the language in the same file.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
What's Next?
Now that you know a little more about ActionScript 3.0 and the Flash Platform, it's time for a look at some of the fundamentals of the language. By reviewing version-independent concepts at the outset, we can focus on new syntax in subsequent chapters. If you have a lot of experience with ActionScript 1.0 or 2.0, you may wish to skim this material.
In the next chapter, we'll discuss:
  • Basic concepts to bring you up to speed quickly, including using the trace() method as a diagnostic tool to see immediate feedback from your scripts
  • Using variables to store data, including arrays and custom objects that allow you to easily manage more than one value, and data typing those values to improve error reporting
  • Logical structures such as conditionals for decision making and loops for simplifying repetitive tasks
  • Functions that can isolate code into convenient blocks that will be executed only when instructed
  • Ways to address Flash objects with ActionScript, including using absolute and relative paths, and the shortcut identifier this
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 2: CORE LANGUAGE FUNDAMENTALS
It's true that ActionScript 3.0 is a complete rewrite of Flash's internal scripting language, and it's also true that ActionScript 3.0 doesn't share the same runtime code base as prior versions of ActionScript. But that's all behind the scenes. The truth is, all versions of ActionScript to date share quite a bit in common.
This is not hard to understand, since ActionScript was based on a scripting language standard (called ECMA-262) that grew from the success of JavaScript, and that ongoing versions of ActionScript are backward compatible to support legacy projects.
That is not to say that the language isn't growing. Certainly, each new version of ActionScript introduces a batch of newly supported features, as is true with the evolution of most programming languages. And, since the decision was made to write ActionScript 3.0 from the ground up, the opportunity presented itself to tidy up a few messy things that lingered from previous versions—namely, tightening up and requiring best practices that had been optional, and restructuring the event and display systems.
All of this progress, however, did not steamroll over the standard upon which ActionScript is based, and most of the language fundamentals remain intact. With the intention to focus on new ActionScript 3.0 options later on, we want to cover some of the more important fundamentals up-front. We do not intend to ignore these ideas throughout the rest of the book. However, because they are core fundamentals and are, therefore, used often, we hope to explain them in sufficient detail here and spend less time on them as we proceed.
If you're already comfortable with ActionScript and are reading this text for a head start learning version 3.0, you may want to skip, or at least skim, this chapter. It is by no means a comprehensive starter course. This book does not assume that you are well versed in any prior version of ActionScript, but its size and purpose requires that we assume a very basic understanding of general scripting concepts. If you haven't already, please look over the Preface for a good idea of who this book is for, as well as a few alternative references if you need more background information.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Miscellaneous Basics
Some basic topics probably don't require a section devoted to their discussion but should still be mentioned due to their use throughout the book. We'll include a few such examples here, just to get us started.
Execution order
In general, ActionScript executes in a top-to-bottom, left-to-right order—that is, each line executes one after another, working from left to right. Several things can change this order in subtle ways, but it's basically a reliable rule of thumb. For example, subroutines of one type or another can be called in the middle of a script, causing the execution order of the original script to pause while the remote routine is executed. When the subroutine has completed, the execution of the original script continues where it left off. These steps will be explained in context, in all scripts in this book.
Use of the semicolon(;)
The official use of the semicolon in ActionScript is to execute more than one instruction on a single line. This is rare in the average script, and we will look at this technique when discussing loops. However, the semi-colon is also used to indicate the end of a line. This is not required, but it is recommended for clarity and to ease any possible transition into learning other languages in which the semicolon at the end of a line is required.
Evaluating an expression
It's helpful to note that you are usually not solving an equation when you see an expression with like values on the left and right of an equal sign. For example if you see something like x = x + 1, it is unlikely that you will be solving for the value of x. Instead, this line is assigning a new value to x by adding 1 to its previous value.
Use of the trace command
As a means of getting quick feedback in an example, or as a testing and debugging technique when writing scripts, it is very helpful to use the trace command. This instruction places any relevant text into the Output panel of the Flash interface. As such, this is an option that is available only at author-time, and has no use at runtime.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Variables and Data Types
Variables are best described as containers into which you place information for later recall. Imagine if you were unable to store any information for later use. You would not be able to compare values against previously described information (such as user names or passwords), your scripts would suffer performance lags due to repeated unnecessary calculations, and you wouldn't be able to carry any prior experiences through to the next possible implementation of a task. In general, you wouldn't be able to do anything that required data that your application had to "remember."
Variables make all this and more possible, and are relatively straightforward. In basic terms, you need only create a variable with a unique name, so it can be referenced separately from other variables and the ActionScript language itself, and then populate it with a value. A simple example is remembering the number 1 with the following:
myVariable = 1;
There are just a few rules and best practices to consider when naming variables. They must be one word, can only include alphanumeric characters along with the dollar sign ($) or underscore (_), should not start with a number, and should not already be a keyword or reserved word in ActionScript.
To help ensure that you are using variables appropriately, ActionScript will monitor them and warn you if you are trying to perform an illegal operation on them, or otherwise use them incorrectly. For example, if you try to perform a mathematical operation on a passage of text, Flash will issue a warning so you can correct the problem.
To do this, Flash must be told what you intend to store in each variable. This is accomplished by declaring the variable by preceding its first use with the var keyword, and citing the type of data to be stored therein by following the name of the variable with a colon (:) and data type. For instance, the previous example of remembering the number 1 should be written this way:
var myVariable:Number = 1;
There are several native data types including, but not limited to, those listed in :
Table :
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Conditionals
You will often have the need to make a decision in your script, choosing to do one thing under one circumstance, and another thing under a different circumstance. These situations are usually addressed by conditionals. Put simply, a test is created, asking whether a condition is met. If the condition is met, the test evaluates to true, and specific code is executed accordingly. If the condition is not met, either no further action is taken or an alternate set of code is executed.
Throughout this book, the code examples are syntax-colored in the same way that the Flash interface colors scripts. This helps identify colored items as part of the ActionScript lexicon (such as keywords and identifiers) and makes it a bit easier to see comments (descriptive text passages that are not executed) and strings.
The most common form of the conditional is the if statement. The statement's basic structure is the if keyword, followed by parentheses in which the conditional test resides, and braces in which the code resides that is executed when the statement evaluates to true. The first three lines in the following example establish a set of facts. The if statement evaluates the given facts. (This initial set of facts will be used for this and subsequent examples in this section.)
var a:Number = 1;
var b:String = "hello";
var c:Boolean = false;

if (a == 1) {
    trace("option a");
}
To evaluate the truth of the test inside the parentheses, conditionals often make use of comparison and logical operators. A comparison operator compares two values, such as equals (==), less than (<), and greater than or equal to (>=), to name a few.
The test in this example uses a double equal sign. This is a comparison operator that asks, "Is this equal to?" This distinction is very important because the accidental use of a single equal sign will cause unexpected results. A single equal sign is an assignment operator and assigns the value in the right side of the equation to the object in the left side of the equation. Because this assignment occurs, the test will always evaluate to true.
A logical operator evaluates the logic of an expression. Included in this category are AND (
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Loops
It is quite common to execute many repetitive instructions in your scripts. However, including them line by line, one copy after another, is inefficient and difficult to edit and maintain. Wrapping repetitive tasks in an efficient structure is the role of loops. A programming loop is probably just what you think it is: Use it to go through the structure and then loop back to the start and do it again. There are a few kinds of loops, and the type you choose to use can help determine how many times your instructions are executed.
The first type of loop structure we'll look at is the for loop. This loop executes its contents a finite number of times. For example, you may wish to create a grid of 25 movie clips or check to see which of 5 radio buttons has been selected. In our first example, we want to trace content to the Output panel three times.
To loop through a process effectively, you must first start with an initial value, such as 0, so you know you have not yet traced anything to the Output panel. The next step is to test to see whether you have exceeded your limit. The first time through, 0 does not exceed the limit of three times. The next step is to trace the content once, and the final step is to increment your initial value, registering that you've traced the desired content once. The process then starts over until, ultimately, you will exceed the limit of the loop. The syntax for a basic for loop is as follows:
for (var i:Number = 0; i < 3; i++) {
    trace("hello");
}
The first thing you may notice is the declaration and typing of the counter, i. This is a common technique because the i variable is often used only for counting and, therefore, is created on the spot and not used again. If you have already declared and typed the counter previously, that step can be omitted here. Next is the loop test. In this case, the counter variable must have a value that is less than 3. Finally, the double-plus sign (++) is equivalent to i = i + 1, or add 1 to the current value of i. The result is three occurrences of the word "hello" in the Output panel.
It is also possible to count down by reversing the values in steps 1 and 2, and then decrementing the counter:
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Arrays
Basic variables can contain only one value. If you set a variable to 1 and then set that same variable to 2 in the following line, the value would be reassigned, and the value of the variable would be 2.
However, there are times when you need one variable to contain more than one value. Think of a hypothetical set of groceries, including 50 items. The standard variable approach to this problem would be to define 50 variables and populate each with a grocery item. That is the equivalent of 50 pieces of paper, each with one grocery item written on its face. This is unwieldy and can only be created at author time—at which point the process is fixed—and you'd have to recall and manage all variable names every time you wanted to access the grocery items.
An array equivalent, however, is very much like how we handle this in real life. A list of 50 grocery items is written on one piece of paper. You can add to the list while at the store, cross each item off once it is acquired, and you only have to manage one piece of paper.
Creating an array is quite easy. You can prepopulate an array by setting a variable (typed as an Array) to a comma-separated list of items, surrounded by brackets. You can also create an empty array by using the Array class. Both techniques are illustrated here:
var myArray:Array = [1, 2, 3]
var yourArray:Array = new Array();
In both cases, you can add to, or remove from, the array at runtime. For example, you can add a value to an array using the push() method, which pushes the value into the array at the end. In short, a method is an action performed by an object—in this case adding something to the array—and will be discussed in detail in the next chapter. You can remove an item from the end of an array using the pop() method.
var myArray:Array = new Array();
myArray.push(1);
trace(myArray)
// 1 appears in the Output panel
myArray.push(2);
// the array now has two items: 1, 2
trace(myArray.pop());
// the pop() method removes the last item, displaying its value of 2
trace(myArray)
// the lone remaining item in the array, 1, is displayed
Both methods are added to the end of the
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Functions
Functions are an indispensable part of programming in that they wrap code into blocks that can be executed only when needed. They also allow code blocks to be reused and edited efficiently, without having to copy, paste, and edit repeatedly. Without functions, all code would be executed in a linear progression from start to finish, and edits would require changes to every single occurrence of any repeated code.
Creating a basic function requires little more than surrounding the code you wish to trigger at will with a simple syntax that allows you to give the block a name. Triggering that function later requires only that you call the function by name. The following syntax shows a function that traces a string to the Output panel. The function is defined and then, to illustrate the process, immediately called. (In a real-world scenario, the function is usually called at some other time or from some other place, such as when the user clicks a button with the mouse.) The output is depicted in the comment that follows the function call.
function showMsg(){
    trace("hello");
}
showMsg();
//hello
If reusing code and executing code only when needed were the only advantage of functions, you'd already have a useful enhancement to linear execution of ActionScript, because it would allow you to group your code into subroutines that could be triggered at any time and in any order. However, you can do much more with functions to gain even greater power.
For example, assume you need to vary the purpose of the previous function slightly. Let's say you need to trace ten different messages. To do that without any new features, you'd have to create ten functions and vary the string that is sent to the Output panel in each function.
However, this can be more easily accomplished with the use of arguments, or very local variables that have life only within their own functions. By adding an argument to the function declaration, in this case the string argument msg, you can pass a value into that argument when you call the function. By using the argument in the body of the function, it takes on whatever value was sent in. In this example, the function no longer traces "hello" every time it is called. Instead, it traces whatever text is sent into its argument when the function is called. When using arguments, it is necessary to type the data coming in so Flash knows how to react and can issue any warnings needed to notify you of errors.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Custom Objects
After just a short while working with ActionScript, you will realize that you are immersed neck-deep in objects. Most discrete entities in ActionScript are descendents of the Object class and tend to behave in a consistent reliable manner. Central to this behavior is the ability for an object to have properties (which are essentially descriptive elements that contribute to the object's general characteristics, like width, location, rotation, and so on), methods (which are actions the object can perform), and even events (custom events that, like a mouse click or a key press, can trigger other processes in the course of working with a script).
You can also create custom objects and define your own properties, methods, and events. To demonstrate this, we'll create a custom object called plane, and give it properties for pitch, roll, and yaw. These properties are terms that describe rotation in 3D space. If you think of yourself seated in a plane, pitch is the angle of rotation that would cause the nose of the plane to go down or up. Roll is the angle of rotation that would cause the plane to spin along the length of the plane, keeping the nose facing forward as you spiral through flight. Finally, yaw is the angle of rotation that comes up perpendicularly through your seat on the plane, causing the plane to spin in a flat spin where the nose would no longer remain facing forward.
None of these terms—plane, pitch, roll, or yaw—are part of the ActionScript library. However, by creating a custom object, we will temporarily make them available to our scripts as if they were always there. The first step in this process is to create the object. Once created, we can add and populate properties:
var plane:Object = new Object();
plane.pitch = 0;
plane.roll = 5;
plane.yaw = 5;
These values would send the plane in a slow right-hand turn. They can be called up at any time, by querying the properties the same way they were created.
trace(plane.pitch);
//0
Creating a custom object to contain properties is a highly effective way of sending multiple optional parameters into a function. ActionScript 3.0 does not like having a variable number of arguments or values for those arguments. If you specify five arguments, it expects five parameters and will balk if you choose to omit any. If you plan your code ahead and plan to allow a series of optional parameters, it is easy to transmit an unknown number of parameter values through a fixed single argument that contains an object. You can then parse the values from this object inside the function, initializing the starting value of any specific properties that were omitted. Here is an example, using the previously created
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
this
Although a bit nebulous for some just starting with ActionScript, this can be your friend. It is essentially shorthand for "whichever object or scope you're working with now." Scope is the realm or space within which an object lives. For example, think of a movie clip inside Flash's main timeline. Each of these objects has a unique scope, so a variable or function defined inside the movie clip will not exist in the main timeline, and vice versa.
It is easiest to understand the usage of this in context, but here are a couple of examples to get you started. If you wanted to refer to the width of a nested movie clip called mc from within the main timeline, you might say:
this.mc.width;
If you wanted to refer to the main timeline from the nested movie clip, you might write:
this.parent.mc.width;
In both cases, this is a reference point from which you start your path. It is fairly common to drop the keyword when going down from the current scope (as in the first example), but it is required when going up to a higher scope (as in the second example). This is because Flash must understand what the parent is actually a parent of in order to start traversing through the hierarchy. Imagine a family reunion in which several extended family members, including cousins and multiple generations, are present, and you are looking for your mother, father, or grandparent. If you just said "parent," any number of parents might answer. If you, instead, said "my parent" or "my mother's parent," that would be specific enough to get you headed in the right direction.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Absolute versus Relative Addresses
Much like a computer operating system's directory, or the file structure of a web site, ActionScript refers to the address of its objects in a hierarchical fashion. You can reference an object address using an absolute or relative path. Absolute paths can be easy because you most likely know the exact path to any object starting from the main timeline. However, they are quite rigid and will break if you change the nested relationship of any of the referenced objects. Relative paths can be a bit harder to call to mind at any given moment, but they are quite flexible. Working from a movie clip and going up one level to its parent and down one level to a sibling will work from anywhere—be that in the root timeline, another movie clip, or nested even deeper—because the various stages aren't named.
and draw parallels to the operating system and web site analogies:
Table : Absolute (from main timeline to nested movie clip)
ActionScript
Windows OS
Mac OS
Web Site
root.mc1.mc2
c:\folder1\folder2
Macintosh/folder1/folder2
Table : Relative (from a third movie clip, up to the root, and down to the child of a sibling)
ActionScript
Windows OS
Mac OS
Web Site
this.parent.mc1.mc2
..\folder1\folder2
../folder1/folder2
../dir/dir
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
What's Next?
Ideally, we've provided just enough background (or review) of key ActionScript fundamentals to now focus in on topical syntax. Although we won't entirely ignore basic elements within the scripts of future chapters, we will spend more time describing the collective goal of a script, and highlighting new issues introduced or updated by ActionScript 3.0.
Next, we start off the ActionScript 3.0-specific material with a look at the three essential building blocks of most ActionScript objects: properties, methods, and events—the latter being one of the most significantly changed elements of ActionScript, with the introduction of version 3.0.
In the next chapter, we'll discuss:
  • The descriptive properties (such as width, height, location, alpha (opacity), rotation, and more) of each object that define its major characteristics
  • The actions you may exert on objects, or that objects may take on other objects, in the form of methods
  • The events issued by the user, or aspects of your program or environment, and, perhaps more directly, the reactions to those events
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 3: PROPERTIES, METHODS, AND EVENTS
In addition to the core language fundamentals reviewed in the previous chapter, you will find that the majority of your scripts are written using properties, methods, and events. These are the basic building blocks of most scripted tasks and allow you to get and set characteristics of, issue instructions to, and react to input from, many Flash elements.
  • Properties. Properties are somewhat akin to adjectives in that they describe the object being modified or queried. For example, you can check or set the width of a button. Most properties are read-write, in that you can both get and set their values. Some properties, however, are read-only, which means you can ask for, but not change, their values.
  • Methods. Methods are a bit like verbs. They are used to tell objects to do something, such as play and stop. In some cases, methods can be used to simplify the setting of properties. You might use a method called setSize(), for example, to simultaneously set the width and height of something. Other methods are more unique, such as navigateToURL(), which instructs a browser to display a web page.
  • Events. Events are the catalysts that trigger the actions you write, setting properties and calling methods. For instance, a user might click the mouse button, which would then result in a mouse event. That event then causes a function to execute, performing the desired actions. Event handlers are the ActionScript middlemen that trap the events and actually call the functions. ActionScript 3.0 has unified event handling into a consistent system of what are called event listeners, which are set up to listen for the occurrence of a specific event and react accordingly.
In this chapter, you will build a utility that will demonstrate each of these ActionScript structures. By creating mouse and keyboard events, you will manipulate several common properties, as well as execute a few methods. The vast majority of ActionScript entities have properties, methods, and events. For clarity, we will focus primarily on the movie clip. Using the movie clip to centralize our discussion will make it easier for you to consult the Flash help system, online resources, and supplemental texts for additional information, as you look for other attributes to manipulate.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Inherited Attributes
One of the most important things to understand when consulting attributes is that ActionScript entities often share attributes in common with other entities. One reason for this is that they may be related in some way, such as being descendents from a common parent. In this case, the child inherits attributes from its parent. We introduced this concept a bit in when we talked about classes. Consider the idea that a daughter, by virtue of being a different sex than her father, has several characteristics, or properties, that are distinct from her father. However, they also may share several characteristics in common, such as eye and hair color.
We will look at the sharing of attributes in greater depth throughout this book but, for now, all you need to know is that ActionScript reference materials are often organized by classes, and it would be redundant and cumbersome to list the same properties for every related class. Considering the movie clip, for example, every Flash element that can be displayed on stage—the movie clip among them—can have an x and a y coordinate, or location, on the stage. Listing these properties for every such item would eat up a lot of space and make the resource a bit harder to wade through.
To simplify things, the x and y properties are typically listed as inherited properties, as is true in the Flash help system. To view inherited properties, for example, in the Flash help system, just click the Show Inherited Public Properties link found immediately under the Public Properties header.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Properties
If you think of properties as ways of describing an object, they become second nature. Asking where a movie clip is, for example, or setting its width are both descriptive steps that both use properties.
In , we briefly discussed the object model and dot syntax that brings order and structure to ActionScript as well as many other scripting and programming languages. Referencing a property begins with an instance—let's call our square movie clip "box"—because you must decide which element you wish to query or change. If we consider a test file with only one movie clip in it, instantiated as "box," all that remains is referencing the property and either getting or setting its value.
To begin, we'll show you the syntax for making five changes to movie clip properties in the following table. Then, when we demonstrate how to handle events in the next section, we'll change these properties interactively. The following examples assume a movie clip of a square is on the stage, and has an instance name of "box." demonstrates the visual change made by each property. The light colored square is the original state when the movie clip is moved. (The alpha property shows only the final state.) The dashed stroke for the visible property is only to show that the box is not visible.
represents six movie clip properties with sample syntax and notes regarding each property's unit of measure and possible sample range of values.
Table : Movie clip properties
Description
Property
Syntax for Setting Value
Units and/or Range
Location
x, y
box.x = 100;
box.y = 100;
pixels
Scale (1)
scaleX, scaleY
box.scaleX = .5;
box.scaleY = .5;
percent / 0–1
Scale (2)
width, height
box.width = 72;
box.height = 72;
pixels
Rotation
rotation
box.rotation = 45;
degrees / 0–360
Transparency
alpha
box.alpha = .5;
percent / 0–1
Visibility
visible
box.visible = false;
Boolean
Figure : Changes to five movie clip properties
If you have experience with prior versions of ActionScript, you may notice a few changes in the property syntax. First, the properties do not begin with an underscore. This is a beneficial consistency introduced with ActionScript 3.0. Rather than varying property syntax, some with and some without leading underscores, no properties begin with the underscore character.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Events
Events make the Flash world go 'round. They are responsible for setting your scripts in motion, causing them to execute. A button can be triggered by a mouse event, text fields react to keyboard events—even calling your own custom functions is a means of issuing a custom event.
Events come in many varieties. In addition to the obvious events like mouse and keyboard input, most ActionScript classes have their own events. For example, events are fired when watching a video, working with text, and resizing the stage. To take advantage of these events to drive your application, you need to be able to detect their occurrences.
In previous versions of ActionScript, there were a variety of ways to trap events. You could apply a script directly to a button, for example, and use the on(Release) approach. As the language matured, you could create event handlers and apply them remotely using instance names, using myButton.onRelease for example. Finally, you could use event listeners, primarily with components or custom objects.
In ActionScript 3.0, trapping events is simplified by relying on one approach for all event handling, which is to use event listeners regardless of the type of event or how it is used. The EventDispatcher class that "oversees" event listeners is not new, but it has been improved and is now responsible for handling the majority of events in AS3.
The EventDispatcher class allows you to listen for the occurrence of events by putting event listeners into service, clean up your code by removing unneeded listeners from service, and manually dispatching events when you need an event to occur at a specific time. You can also check to see whether an object has a listener already set up for a specific event, which we'll look at later when we talk about event propagation.
The concept of event listeners is pretty simple. Imagine that you are in a lecture hall that holds 100 people. Only one person in the audience has been given instructions about how to respond when the lecturer asks a specific question. In this case, one person has been told to listen for a specific event, and to act on the instructions provided when this event occurs.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Methods
Methods, the verbs of the ActionScript language, instruct their respective objects to take action. For example, you can tell a movie clip to stop playing by using its stop() method. Like properties, methods appear consistently in the dot syntax that is the foundation of ActionScript, following the object calling the method. For example, if the movie clip "box" in the main timeline issues the stop() method, the syntax would appear like this:
box.stop();
Also like properties, most ActionScript classes have specific methods, and many inherit methods from ancestor classes. In addition, like properties, you can further define your own methods by writing functions in your own custom classes. For the following demonstration, we'll again focus on the movie clip from the prior example. This time, however, we'll introduce another event class and show you how to control your movie clips with the keyboard.
Trapping keyboard events is very similar to trapping mouse events, with one significant exception: The target of the event listener is not frequently the object you wish to manipulate. When working with text, the text field being manipulated may, indeed, serve well as the target of the keyboard events. When controlling movie clips, however, the stage itself is often a useful, centralized recipient of the keyboard events.
Adding an event listener to the stage means that you can process all key events with a single listener, and then isolate only the desired key events with a conditional, issuing instructions accordingly. To simplify the syntax of this last segment of our demonstration script, we'll use the switch form of conditional statements. The switch statement, reviewed in , is simply a more easily readable if/else-if conditional structure.
We'll start by adding the listener to the stage. In this case, we'll be looking for the key down event, which is specified using a constant like most predefined events, but this time it is part of the KeyboardEvent class. When the event is heard, our listener will call the onKeyPressed() function.
1 stage.addEventListener(KeyboardEvent.KEY_DOWN, onKeyPressed);
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Event Propagation
So far in this chapter, we've been working with objects in the display list. We'll explain the display list in greater detail in the next chapter but, in essence, the display list contains all visual objects in your file. It includes the stage, any loaded SWFs, and any shapes, buttons, movie clips, and so on, down to the most deeply nested clip.
Objects in the display list are part of a special event flow often referred to as event propagation. When the target of certain events, including mouse and key events, is in the display list, the event is not dispatched directly to the event target. Instead, it is dispatched to the display list, and the event propagates from the top of the list down to the event target, and then bubbles (works its way) back up through the display list again.
Consider two movie clips (mc2 and mc3) within a movie clip (mc1) that is on the stage. Next, imagine that the target of the event is the nested movie clip, mc2. When the desired event occurs, it is not dispatched directly to mc2, but rather to the display list. First, the stage receives the event, then any relevant loaded SWFs (including the root timeline, in this example), then the parent movie clip, mc1, and then the target of the event, mc2. After the event is received by the target, it then propagates back up through the display list to mc2, root, and stage. depicts the process, showing a mouse event dispatched to the top of the display list, the stage, making it's way through the root timeline and parent movie clip until it reaches the event target, and then bubbling back up through the display list again.
Figure : Event propagation process
Event propagation can be used to great advantage with just a little bit of planning. For example, let's say both nested movie clips were designed to react to mouse over and mouse out events. Whenever the user rolled the mouse over one of the clips, it would change it alpha value to indicate interaction. In this case, you would normally have to attach a listener for each event to each movie clip. The code for such an example follows, and depicts the result, where each movie clip is represented by a folder:
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Frame and Timer Events
We have been using mouse and keyboard events because you are almost certainly familiar with them to some degree, and they are ideally suited to this tutorial context. However, there are many, many events in the ActionScript language. While it's not possible to cover every one, we would like to round out the chapter with two significant other event types: frame and timer.
Frame events are not triggered by user input, the way mouse and keyboard events are. Instead, they occur naturally as the Flash file plays. Each time the playhead enters a frame, a frame script is executed. This means that frame scripts execute only once for the life of the frame, making them an excellent location for seldom-executed tasks, such as initializations. In other words, for a frame script to execute more than once, the playhead must leave the frame and return—either because of an ActionScript navigation instruction, or a playback loop that returns the playhead to frame 1 when it reaches the end of the timeline.
However, using an event listener, you can listen for a recurring enter frame event that some display objects have, including the main timeline and the movie clips. An enter frame event is fired