-
Using ActionScript in Flash
-
Trademarks Add Life to the Web, Afterburner, Aftershock, Andromedia, Allaire, Animation PowerPack, Aria, Attain, Authorware, Authorware Star, Backstage, Bright Tiger, Clustercats, ColdFusion, Contribute, Design In Motion, Director, Dream Templates, Dreamweaver, Drumbeat 2000, EDJE, EJIPT, Extreme 3D, Fireworks, Flash, Flash Lite, Flex, Fontographer, FreeHand, Generator, HomeSite, JFusion, JRun, Kawa, Know Your Site, Knowledge Objects, Knowledge Stream, Knowledge Track, LikeMinds, Lingo, Live Effects, MacRec
-
CONTENTS INTRODUCTION: Getting Started with ActionScript ....................... 7 Intended audience . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . System requirements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Using the documentation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Typographical conventions . . . . . . . . . . . . . . . . . . . . . . . . . . .
-
Behaviors conventions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 105 Screens conventions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 107 Video conventions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 110 Performance and Flash Player . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 114 Guidelines for Flash applications . . . . . . . . .
-
Adding parameters to dynamically created movie clips . . . . . . . . . . . . . . . . . . . . Managing movie clip depths . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Drawing shapes with ActionScript. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Using movie clips as masks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . About masking device fonts. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
-
APPENDIX A: Error Messages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 305 APPENDIX B: Deprecated Flash 4 operators . . . . . . . . . . . . . . . . . . . . . . . . . . . 311 APPENDIX C: Keyboard Keys and Key Code Values . . . . . . . . . . . . . . . . . . . . . 313 Keys on the numeric keypad . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 314 Function keys . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
-
INTRODUCTION Getting Started with ActionScript Macromedia Flash MX 2004 and Macromedia Flash MX Professional 2004 are the professional standard authoring tools for producing high-impact web experiences. ActionScript is the language you use to add interactivity to a Flash applications, whether your applications are simple animated movies or more complex rich Internet applications.
-
• Chapter 1, “What’s New in Flash MX 2004 ActionScript,” on page 11 describes features that are new in ActionScript, changes to the compiler and debugger, and the new programming model for the ActionScript 2.0 language. • Chapter 2, “ActionScript Basics,” on page 23 describes the terminology and basic concepts used in the rest of the manual. • Chapter 3, “Using Best Practices,” on page 65 helps explain the best practices for using Flash and writing ActionScript.
-
Before writing your own scripts, you should complete the lessons “Write Scripts with ActionScript” and “Create a Form with Conditional Logic and Send Data,” which provide a hands-on introduction to working with ActionScript. To find these lessons, select Help > How Do I > Quick Tasks. When you find information about a certain command you want to use, you can look up its entry in ActionScript Language Reference Help.
-
The Macromedia DevNet website (www.macromedia.com/devnet) is updated regularly with the latest information on Flash, plus advice from expert users, advanced topics, examples, tips, and other updates. Check the website often for the latest news on Flash and how to get the most out of the program. The Macromedia Flash Support Center (www.macromedia.com/support/flash) provides TechNotes, documentation updates, and links to additional resources in the Flash community.
-
CHAPTER 1 What’s New in Flash MX 2004 ActionScript Macromedia Flash MX 2004 and Macromedia Flash MX Professional 2004 provide several enhancements that make it easy for you to write robust scripts using the ActionScript language.
-
New and changed language elements This section describes the ActionScript language elements that are new or changed in Flash MX 2004. To use any of these elements in your scripts, you must target Flash Player 7 (the default) when you publish your documents. • The Array.sort() and Array.sortOn() methods let you add parameters to specify additional sorting options, such as ascending and descending sorting, whether to consider casesensitivity when sorting, and so on. • The Button.menu, MovieClip.
-
• The TextField.condenseWhite property lets you remove extra white space from HTML text fields that are rendered in a browser. • The TextField.mouseWheelEnabled property lets you specify whether a text field’s contents should scroll when the mouse pointer is positioned over a text field and the user rolls the mouse wheel. • The “TextField.StyleSheet class” lets you create a style sheet object that contains text formatting rules such as font size, color, and other formatting styles. • The TextField.
-
Also, Flash Player 7 implements several changes that affect how one SWF file can access another SWF file, how external data can be loaded, and how local settings and data (such as privacy settings and locally persistent shared objects) can be accessed. Finally, the behavior of some existing features has changed.
-
SWF file published for Flash Player 7 SWF file published for earlier versions of Flash Player When undefined is converted to a string, the result is When undefined is converted to a string, the result is an empty string (""). undefined.
-
In files published for Flash Player 5 or earlier, there were no restrictions on cross-domain or subdomain access. In files published for Flash Player 6, you could use the LocalConnection.allowDomain handler or System.security.allowDomain() method to specify permitted cross-domain access (for example, to let a file at someSite.com be accessed by a file at someOtherSite.com), and no command was needed to permit subdomain access (for example, a file at www.someSite.com could be accessed by a file at store.
-
You might also have to add statements such as these to your files if you aren’t currently using them. For example, if your SWF file is hosted at www.someSite.com and you want to allow access by a SWF file published for Flash Player 7 at store.someSite.com, you must add statements such as the following example to the file at www.someSite.com (you can still publish the file at www.someSite.com for Flash Player 6): System.security.allowDomain("store.someSite.com"); my_lc.
-
HTTP to HTTPS protocol access between SWF files As discussed in the previous section, rules for cross-domain and subdomain access have changed in Flash Player 7. In addition to the exact-domain matching rules now being implemented, you must explicitly permit files hosted at sites using a secure protocol (HTTPS) to be accessed by files hosted at sites using an insecure protocol.
-
• If the called file is published for Flash Player 6 or earlier, and both the calling and called files are in same domain (for example, a file in http://www.domain.com is calling a file in https:// www.domain.com), no modification is needed. • If the called file is published for Flash Player 6, the files are not in same domain, and you don’t want to port the called file to Flash Player 7, modify the called file to add or change a System.security.allowDomain or LocalConnection.
-
ActionScript editor changes The ActionScript editor has been updated in several ways to make it more robust and easier to use. These changes are summarized in this section. Word wrapping You can now use the Options pop-up menu in the Script pane, Debugger panel, and Output panel to enable or disable word wrapping. You can also toggle word wrapping using the pop-up menu on the Actions panel. The keyboard shortcut is Control+Shift+W (Windows) or Command+Shift+W (Macintosh).
-
Debugging changes This section describes changes that improve your ability to debug your scripts. Output window changed to Output panel You can now move and dock the Output panel in the same way as any other panel in Flash. Improved error reporting at compile time In addition to providing more robust exception handling, ActionScript 2.0 provides several new compile-time errors. For more information, see Appendix A, “Error Messages,” on page 305.
-
• • • • • • • • interface dynamic static public private get set import Key facts about ActionScript 2.0 include the following points: • Scripts that use ActionScript 2.0 to define classes or interfaces must be stored as external script files, with a single class defined in each script; that is, classes and interfaces cannot be defined in the Actions panel.
-
CHAPTER 2 ActionScript Basics ActionScript has rules of grammar and punctuation that determine which characters and words are used to create meaning and in which order they can be written. For example, in English, a period ends a sentence; in ActionScript, a semicolon ends a statement. 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 its entry in Flash ActionScript Language Reference.
-
Differences between ActionScript and JavaScript ActionScript is similar to the core JavaScript programming language. You don’t need to know JavaScript to use and learn ActionScript; however, if you know JavaScript, ActionScript will seem familiar. This manual does not attempt to teach general programming. There are many resources that provide more information about general programming concepts and the JavaScript language.
-
Constructors are functions that you use to define (initialize) the properties and methods of a class. By definition, constructors are functions within a class definition that have the same name as the class. For example, the following code defines a Circle class and implements a constructor function: // file Circle.as class Circle { private var circumference:Number; // constructor function Circle(radius:Number){ this.circumference = 2 * Math.
-
Instance names are unique names that let you target instances you create, or movie clip and button instances on the Stage. For example, in the following code, “names” and “studentName” are instance names for two objects, an array and a string: var names:Array = new Array(); var studentName:String = new String(); You use the Property inspector to assign instance names to instances on the Stage.
-
Operators are terms that calculate a new value from one or more values. For example, the addition (+) operator adds two or more values together to produce a new value. The values that operators manipulate are called operands. Parameters (also called arguments) are placeholders that let you pass values to functions.
-
Syntax As with all scripting languages, ActionScript has syntax rules that you must follow to create scripts that can compile and run correctly.
-
Case-sensitivity is implemented on a per-movie basis. If a strict Flash Player 7 application calls a non-strict Flash Player 6 movie, ActionScript executed in the latter movie is non-strict. For example, if you use loadMovie() to load a Flash Player 6 SWF into a Flash Player 7 SWF, the version 6 SWF remains case-insensitive, while the version 7 SWF is treated as case-sensitive. When syntax coloring is enabled, language elements written with correct capitalization are blue by default.
-
Slash syntax Slash syntax was used in Flash 3 and 4 to indicate the target path of a movie clip or variable. This syntax is still supported by Flash Player 7, but its use is not recommended, and slash syntax is not supported in ActionScript 2.0. However, if you are creating content intended specifically for Flash Player 4, you must use slash syntax. For more information, see “Using slash syntax” on page 321.
-
Semicolons An ActionScript statement is terminated with a semicolon (;), as shown in the following examples: var column:Number = passedDate.getDay(); var row:Number = 0; If you omit the terminating semicolon, Flash still compiles your script successfully. However, it is good scripting practice to use semicolons because it makes your code more readable.
-
As shown in the following example, to indicate that a line or portion of a line is a comment, precede the comment with two forward slashes (//): my_btn.onRelease = function() { // create new Date object var myDate:Date = new Date(); var currentMonth:Number = myDate.getMonth(); // convert month number to month name var monthName:String = calcMonth(currentMonth); var year:Number = myDate.getFullYear(); var currentDate:Number = myDate.
-
eq extends finally for function ge get gt if ifFrameLoaded implements import in instanceof interface intrinsic le lt ne new not on onClipEvent or private public return set static switch tellTarget this throw try typeof var void while with All class names, component class names, and interface names are reserved words: Accessibility Accordion Alert Array Binding Boolean Button Camera CellRenderer CheckBox Collection Color ComboBox ComponentMixins ContextMen
-
WebServiceConnector Window XML XMLConnector XUpdateResolver Constants A constant is a property whose value never changes. ActionScript contains predefined constants. For example, the constants BACKSPACE, ENTER, SPACE, and TAB are properties of the Key object and refer to keyboard keys. To test whether the user is pressing the Enter key, you could use the following statement: if(Key.getCode() == Key.ENTER) { alert = "Are you ready to play?"; control_mc.
-
You can convert one data type to another using one of the following conversion functions: Array(), Boolean(), Number(), Object(), String(). In ActionScript 2.0, you can assign data types to variables when you initialize them. The data types you assign can be any of the built-in types or can represent a custom class that you’ve created. For more information, see “Strict data typing” on page 41. String data type A string is a sequence of characters such as letters, numbers, and punctuation marks.
-
Number data type The number data type is a double-precision floating-point number. The minimum value of a number object is approximately 5e-324. The maximum is approximately 1.79E+308. You can manipulate numbers using the arithmetic operators addition (+), subtraction (-), multiplication (*), division (/), modulo (%), increment (++), and decrement (--). For more information, see “Numeric operators” on page 51. You can also use methods of the built-in Math and Number classes to manipulate numbers.
-
} }; submit_button.addEventListener("click", btnListener); For more information, see “Using built-in functions” on page 60 and “Logical operators” on page 53. Object data type An object is a collection of properties. Each property has a name and a value. The value of a property can be any Flash data type—even the object data type. This lets you arrange objects inside each other, or nest them. To specify objects and their properties, you use the dot (.) operator.
-
my_mc.startDrag(true); parent_mc.getURL("http://www.macromedia.com/support/" + product); The second example returns the width of a movie clip called my_mc on the Stage. The targeted instance must be a movie clip, and the returned value must be a numeric value. function getMCWidth(target_mc:MovieClip):Number { return target_mc.
-
Null data type The null data type has only one value, null. This value means no value—that is, a lack of data. You can assign the null value in a variety of situations to indicate that a property or variable does not yet have a value assigned to it.
-
• Values returned from a function or method • Objects created as subclasses of existing classes In ActionScript 2.0, you should explicitly assign data types to items, which can help prevent or diagnose certain errors in your scripts at compile time and offers other benefits. This technique is called strict data typing.
-
Strict data typing ActionScript 2.0 lets you explicitly declare the object type of a variable when you create it, which is called strict data typing. Strict data typing offers several benefits at compile time. Because data type mismatches trigger compiler errors, strict data typing helps you find bugs in your code at compile time and prevents you from assigning the wrong type of data to an existing variable.
-
Using strict typing also helps to ensure that you do not attempt to access properties or methods that are not part of an object’s type. Another advantage of strict data typing is that Flash MX 2004 automatically shows code hints for built-in objects when they are strictly typed. For more information, see “Strictly typing objects to trigger code hints” on page 145.
-
In this situation, you asserted to the compiler that foo is a Dog object, and, therefore, the compiler assumes that temp.bark(); is a legal statement. However, the compiler doesn’t know that the cast will fail (that is, that you tried to cast a Cat object to an Animal type), so no compiletime error occurs. If you include a check in your script to make sure that the cast succeeds, you can find casting errors at runtime. import Dog; function bark(myAnimal:Animal) { var foo:Dog = Dog(myAnimal); if (foo) { foo.
-
About variables A variable is a container that holds information. The container itself is always the same, but the contents can change. By changing the value of a variable as 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. It’s a good idea always to assign a variable a known value the first time you define the variable.
-
You should not use any element in the ActionScript language as a variable name because it can cause syntax errors or unexpected results. In the following example, if you name a variable String and then try to create a String object using new String(), the new object is undefined: // This code works as expected var hello_str:String = new String(); trace(hello_str.length); // returns 0 // But if you give a variable the same name as a built-in class....
-
Make sure to declare a Timeline variable before trying to access it in a script. For example, if you put the code var x = 10; in Frame 20, a script attached to any frame before Frame 20 cannot access that variable. Local variables To declare local variables, use the var statement inside the body of a function. A local variable declared within a function block is defined within the scope of the function block and expires at the end of the function block.
-
} } count(); trace(counter); // accesses global variable and displays 100 This example simply shows that the global variable is not accessed in the scope of the count() function. To avoid confusion in your applications, name your variables uniquely. The Flash Player version 7 and later security sandbox enforces restrictions when accessing global variables from movies loaded from separate security domains. For more information, see “Flash Player security features” on page 288.
-
In the following example, the variable inValue contains a primitive value, 3, so that value is passed to the sqr() function and the returned value is 9: function sqr(x:Number):Number { var x:Number = x * x; return x; } var inValue:Number = 3; var out:Number = sqr(inValue); trace(inValue); //3 trace(out); //9 The value of the variable inValue does not change, even though the value of x in the function changes.
-
Using operators to manipulate values in expressions 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. Operators are characters that specify how to combine, compare, or modify the values of an expression. The elements that the operator performs on are called operands.
-
When two or more operators share the same precedence, their associativity determines the order in which they are performed. Associativity can be either left-to-right or right-to-left. For example, the multiplication (*) operator has an associativity of left-to-right; therefore, the following two statements are equivalent: total = 2 * 3 * 4; total = (2 * 3) * 4; The following table lists all the ActionScript operators and their associativity, from highest to lowest precedence.
-
Operator Description Associativity instanceof Instance of (finds the class of which the object is an Left to right instance) Requires Flash Player 6 or later < Less than Left to right <= Less than or equal to Left to right > Greater than Left to right >= Greater than or equal to Left to right == Equal Left to right != Not equal Left to right & Bitwise AND Left to right ^ Bitwise XOR Left to right | Bitwise OR Left to right && Logical AND Left to right || Logical OR Left
-
Operator Operation performed / Division % Modulo (remainder of division) - Subtraction ++ Increment -- Decrement Comparison operators Comparison operators compare the values of expressions and return a Boolean value (true or These operators are most commonly used in loops and in conditional statements. In the following example, if the variable score is 100, a certain function is called; otherwise, a different function is called: false).
-
Operator Operation performed <= Less than or equal to: Returns true if the left operand is mathematically smaller than or the same as the right operand. Returns true if the left operand alphabetically precedes or is the same as the right operand. >= Greater than or equal to: Returns true if the left operand is mathematically larger than or the same as the right operand. Returns true if the left operand alphabetically follows or is the same as the right operand.
-
Consider the order of operands, especially if you’re setting up complex conditions and you know how often one condition is true compared with other conditions. In the previous example, if you know that, in most cases, i will be greater than 50, consider putting the condition i<50 first; the condition i<50 will be checked first, and the second condition doesn’t need to be checked in most cases.
-
The strict equality (===) operator is similar to the equality operator, with one important difference: The strict equality operator does not perform type conversion. If the two operands are of different types, the strict equality operator returns false. The strict inequality (!==) operator returns the opposite of the strict equality operator.
-
Operator Operation performed -= Subtraction and assignment *= Multiplication and assignment %= Modulo and assignment /= Division and assignment <<= Bitwise shift left and assignment >>= Bitwise shift right and assignment >>>= Shift right zero fill and assignment ^= Bitwise XOR and assignment |= Bitwise OR and assignment &= Bitwise AND and assignment Dot and array access operators You can use the dot operator (.
-
function barGetProp():String { return "bar"; } function barSetProp(str:String):Void { } bar.addProperty("someProp", barGetProp, barSetProp); //trace(bar.someProp); // generates an error trace(bar["someProp"]); // no error You can use the eval() function to dynamically set and retrieve instance names and variables, as shown in the following example: eval("mc" + i) The array access operator can also be used on the left side of an assignment statement.
-
To dynamically create a movie clip: • Use the MovieClip.attachMovie(), MovieClip.createEmptyMovieClip(), or method. The following example uses the method to dynamically create the purpleDot2_mc movie clip and place it on top of the greenBox_mc movie clip when the user rolls over the greenBox_mc clip, which is on the Stage: MovieClip.duplicateMovieClip() attachMovie() my_btn.onRollOut = function(){ this.greenBox_mc.
-
gotoAndPlay("startProgram"); } If you want to check for one of several conditions, you can use the switch statement rather than multiple else if statements. Repeating actions ActionScript can repeat an action a specified number of times or while a specific condition exists. Use the while, do..while, for, and for..in actions to create loops. To repeat an action while a condition exists: • Use the while statement.
-
To loop through the children of a movie clip or an object: • Use the for..in statement. Children include other movie clips, functions, objects, and variables.
-
Creating functions You can define functions to execute a series of statements on passed values. Your functions can also return values. After a function is defined, it can be called from any Timeline, including the Timeline of a loaded SWF file. A well-written function can be thought of as a “black box.” If it has carefully placed comments about its input, output, and purpose, a user of the function does not need to understand exactly how the function works internally.
-
Passing parameters to a function Parameters are the elements on which a function executes its code. (In this manual, the terms parameter and argument are interchangeable.) For example, the following function takes the parameters initials and finalScore: function fillOutScorecard(initials:String, finalScore:Number):Void { scorecard.display = initials; scorecard.score = finalScore; } When the function is called, the required parameters must be passed to the function.
-
For example, the following function returns the square of the parameter x and specifies that the returned value must be a Number: function sqr(x:Number):Number { return x * x; } Some functions perform a series of tasks without returning a value. For example, the following function initializes a series of global variables: function initialize() { boat_x = _global.boat._x; boat_y = _global.boat._y; car_x = _global.car._x; car_y = _global.car.
-
Chapter 2: ActionScript Basics
-
CHAPTER 3 Using Best Practices It is important for Macromedia Flash designers and developers to build applications or animations while being concerned about writing code and structuring applications in a way that is beneficial either to themselves, or to the other people who might work on the project with them.
-
Therefore, it is particularly useful to follow guidelines in the following situations, and for the following reasons: When working on FLA documents Adopting consistent and efficient practices helps you speed up your workflow. It is faster to develop using best practices, and easier to understand and remember how you structured your document when you edit it further. Additionally, your code is often more portable within the framework of a larger project, and easier to reuse.
-
• Clearly describe the purpose or content of each layer or folder when you name them in a FLA file. This helps users to quickly understand where particular assets are found in layers or folders. It is a good and common practice to name the layer that contains your ActionScript actions and to use layer folders to organize similar layers. • If applicable, place your layers that include ActionScript and a layer for frame labels at the top of the layer stack in the Timeline.
-
There are some situations where few of these disadvantages apply, such as when you create lengthy animations, which is a good time to use scenes. If disadvantages apply to your document, consider using screens to build an animation instead of using scenes. For more information on using screens, see “Creating a new screen-based document (Flash Professional only)” in Using Flash. Saving and version control When you save your FLA files, it is important to consider using a naming scheme for your documents.
-
Caution: When you select Save and Compact, you cannot undo any changes you made before you saved the file. If you select Save when working with a document, you can undo prior to that save point. Because Save and Compact deletes the earlier version of the file and replaces it with the optimized version, you cannot undo earlier changes.
-
Limit your use of abbreviations, but use them consistently. An abbreviation must clearly stand for only one thing. For example, the abbreviation sec might represent section and second. Make sure you use it only for one term, and choose a different abbreviation for the other term. Many developers concatenate words to create names. Use mixed casing when you concatenate words to distinguish between each word for readability. For example, write myPelican rather than mypelican.
-
switch = true; new = "funk"; Always strict data type your variables, which helps avoid errors in your code and trigger code completion. For more information on strict typing and suffixes, see “Using code completion and suffixes” on page 78. You should use suffixes with your variables because suffixes improve ActionScript readability. Try to keep variables as short as possible while retaining clarity. For more information on processing and performance, see “Performance and Flash Player” on page 114.
-
Constants Variables should be lowercase or mixed-case letters; however, constants (variables that do not change) should be uppercase. Separate words with underscores, as the following ActionScript shows: var BASE_URL:String = "http://www.macromedia.com"; var MAX_WIDTH:Number = 10; //constant //constant Write static constants in uppercase, and separate words with an underscore. Do not directly code numerical constants unless the constant is 1, 0, or -1, which you might use in a for loop as a counter value.
-
Classes and objects Class names are usually nouns or qualified nouns, beginning with an uppercase first letter. A qualifier describes the noun or phrase. For example, instead of member, you might qualify the noun using NewMember or OldMember. Sometimes a class name is a compound word. Write class names in mixed case beginning with an uppercase letter when the name includes concatenated words.
-
// or mx.containers.TextInput This convention uses a prefix of mx.containers. If you create your own packages, use a consistent naming convention, such as starting with Or, use a convention of naming your packages com.yourcompany.PackageName. com.macromedia.PackageName. A clear and self-explanatory package name is important because it explains the package’s responsibilities.
-
For more information on Component conventions, see“Working with components in Flash Player” on page 115. Remember that the naming conventions in this section are guidelines. It is most important to use a naming scheme that works well for you and use it consistently. Avoiding reserved words Avoid using reserved words as instance names in Flash. As a general rule, avoid using any word in ActionScript as an instance or variable name.
-
All class names, component class names, and interface names are also reserved words, as listed in the following table: Accessibility Accordion Alert Array Binding Boolean Button Camera CellRenderer CheckBox Collection Color ComboBox ComponentMixins ContextMenu ContextMenuItem CustomActions CustomFormatter CustomValidator DataGrid DataHolder DataProvider DataSet DataType Date DateChooser DateField Delta DeltaItem DeltaPacket DepthManager EndPoint Error FocusManager Form Fun
-
For more information on formatting code, see the following topics: • • • • “Using comments in code” on page 77 “Using code completion and suffixes” on page 78 “Using recommended suffixes” on page 80 “Spacing and readability” on page 81 Using comments in code One of most important aspects of any project, whether it is a simple widget or a large scale application, is documentation. Without comments, it is likely you will not know why code was written or organized in a certain way.
-
Note: If you place the comment characters (/* and */) on separate lines at the beginning and end of the comment, you can easily comment them out by placing double slash characters (//) in front of them (for example, ///* and //*/). This lets you quickly and easily comment and uncomment your code.
-
To strict data type your variables, you must define the variable using the var keyword. In the following example, when creating a LoadVars object, you would use strict data typing: var params_lv:LoadVars = new LoadVars(); Strict data typing provides you with code completion, and ensures that the value of params_lv contains a LoadVars object. It also ensures that the LoadVars object is not used to store numeric or string data.
-
However, the following ActionScript throws an error and does not allow you to use code completion: var myScrollPane:ScrollPane; //no code completion, throws error Using recommended suffixes You can use the following suffixes to generate code completion in the Actions panel. They are recommended because suffixes encourage consistency in code that might be shared among Flash authors. Although suffixes are not necessary for code completion in ActionScript 2.
-
Use the following suffixes with component instances. These suffixes do not generate code completion in the Actions panel. However, using suffixes encourages consistency in ActionScript that might be shared among developers.
-
Use line breaks to make complex statements easier to read You can format some statements, such as conditional statements, in several ways. Sometimes, formatting statements across several lines rather than a single line makes it easier to read. For more information on properly formatting statements, see “Writing syntax and statements” on page 89. Use consistent indentation in your code Indenting helps show the hierarchy of the code’s structure.
-
Keeping actions together Whenever possible, put your ActionScript in a single location. If you put code in a FLA file, put ActionScript on the first or second frame on the Timeline, in a layer called actions that is the first or second layer on the Timeline. Sometimes you might create two layers for ActionScript to separate functions, which is an acceptable practice. Some Flash applications do not always put all your code in a single place (in particular, when you use screens or behaviors).
-
Attaching ActionScript to a button called myButton_btn looks like the following ActionScript, and should be avoided: on (release) { //do something } However, placing ActionScript with the same purpose on the Timeline looks like the following code, which is encouraged: myButton_btn.onRelease = function() { //do something }; For more information on ActionScript syntax, see “Writing syntax and statements” on page 89.
-
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.
-
For more information on guidelines for writing ActionScript, see the following topics: • • • • • • • “Adding initialization” on page 86 “Using trace statements” on page 87 “Using the super prefix” on page 87 “Avoiding the with statement” on page 87 “Using variables” on page 88 “Writing syntax and statements” on page 89 “Following general formatting guidelines” on page 95 Adding initialization One of the easiest ways to initialize code using ActionScript 2.0 is to use classes.
-
Using trace statements Use trace statements in your documents to help you debug your code while authoring the FLA file. For example, by using a trace statement and for loop, you can see the values of variables in the Output panel, such as strings, arrays, and objects, as the following example shows: var day_array:Array = ["sun", "mon", "tue", "wed", "thu", "fri", "sat"]; var numOfDays:Number = day_array.
-
createTextField("label_txt", 100, 0, 20, 100, 22); label_txt.text = "Circle 1"; someVariable = true; } In this code, you attach a movie clip instance from the library and modify its properties using the with statement. When you do not specify a variable’s scope, you do not always know where you are setting properties, so your code can be confusing. In the previous code, you might expect someVariable to be set within the circle1_mc movie clip, but it is actually set in the main Timeline of the SWF file.
-
} } Delete variables or make variables null when you no longer need them. Setting variables to null can still enhance performance. This process is commonly called garbage collection. Deleting variables helps optimize memory use during runtime, because unneeded assets are removed from the SWF file. It is better to delete variables than to set them to null. For more information on performance, see “Performance and Flash Player” on page 114.
-
Writing conditional statements Place conditions put on separate lines in if, else-if, and if-else statements. Your if statements should use braces ({}). You should format braces like the following examples.
-
The shortened if statement syntax is known as the conditional operator (?:). It lets you convert simple if-else statements into a single line of code. In this case, the shortened syntax reduces readability, and so it is not preferable. Do not use this syntax for complex code, because it is more difficult to spot errors. For more information on using conditional operators, see “Writing conditional statements” on page 90 and “Writing compound statements” on page 91.
-
Using the for statement Write the for statement using the following format: for (init; condition; update) { // statements; } The following structure demonstrates the for statement: for (var i = 0; i<4; i++) { myClip_mc.duplicateMovieClip("newClip"+i+"_mc", i+10, {_x:i*100, _y:0}); } Remember to include a space following each expression in a for statement.
-
Using return statements Do not use parentheses [()]with any return statements that have values. The only time you should use parentheses with return statements is when it makes the value more obvious, which is shown in the third line of the following ActionScript: return; return myCar.paintColor(); // parentheses used to make the return value obvious return ((paintColor)? paintColor: defaultColor); Writing switch statements All switch statements include a default case.
-
Using listener syntax There are several ways to write listeners for events in Flash MX 2004. Some popular techniques are shown in the following code examples. The first example shows a properly formatted listener syntax, which uses a Loader component to load content into a SWF file. The progress event starts when content loads, and the complete event indicates when loading finishes. var box_ldr:mx.controls.Loader; var ldrListener:Object = new Object(); ldrListener.
-
Following general formatting guidelines Adding spacing (or white space) to your syntax is recommended because it makes your ActionScript easier to read. The following formatting points are recommended to help promote readability in your ActionScript.
-
• “Using the this keyword” on page 96 • “Using scope in classes” on page 97 Avoiding _root There are several ways to target instances that let you avoid using _root; these are discussed later in this section. Avoid using _root in ActionScript because it can cause SWF files that load into other SWF files to not work correctly. The _root identifier targets the base SWF file that is loading, not the SWF file using relative addressing instead of _root.
-
this.stopDrag(); }; For a class, you can write code in the following format: class User { private var m_username:String; private var m_password:String; function User(username:String, password:String) { this.m_username = username; this.m_password = password; } public function get username():String { return this.m_username; } public function set username(username:String):Void { this.
-
// Begin loading the XML document. prod_xml.load(targetXml_string); } public function init():Void { // Display the XML packet. trace(this.m_products_xml); } } Because you are trying to reference the private member variable within an onLoad handler, the this keyword actually refers to the prod_xml instance and not the Product class, which you might expect. For this reason, you must create a pointer to the local class file so that you can directly reference the class from the onLoad handler.
-
class mx.site.Utils { static function randomRange(min:Number, max:Number):Number { if (min>max) { var temp:Number = min; min = max; max = temp; } return (Math.floor(Math.random()*(max-min+1))+min); } static function arrayMin(num_array:Array):Number { if (num_array.length == 0) { return Number.NaN; } num_array.sort(Array.NUMERIC | Array.DESCENDING); var min:Number = Number(num_array.pop()); return min; } static function arrayMax(num_array:Array):Number { if (num_array.
-
The Flash MX 2004 object model does not support multiple inheritance; it supports only single inheritance. Therefore, a class can come from a single parent class. This parent class can be either a native Flash class or a user-defined class. Flash MX 2004 uses interfaces to provide additional functionality, but only supports single inheritance. For information on interfaces, see “Interfaces” on page 249. For information on implementing inheritance, see “Inheritance” on page 249.
-
Instance variables follow static variables. Write the public member variables first, and follow them with private member variables. Following the public and private member variables, add the constructor statement, such as the one in the following example: public function UserClass(username:String, password:String) {...} Finally, write your methods. Group methods by their functionality, not by their accessibility or scope. Organizing methods this way helps improve the readability and clarity of your code.
-
Programming classes There are several general guidelines for programming classes. These guidelines help you write well-formed code, but also remember to follow the guidelines provided in “General coding conventions” on page 69 and “ActionScript coding standards” on page 82. When you program classes, follow these guidelines: • Do not use objects to access static methods and variables. Do not use myObj.classMethod(); use a class name, such as MyClass.classMethod().
-
There are two kinds of comments in a typical class or interface file: documentation comments and implementation comments. Documentation comments are used to describe the code’s specifications and do not describe the implementation. Implementation comments are used to comment out code or to comment on the implementation of particular sections of code. The two kinds of comments use slightly different delimiters.
-
Using design patterns Design patterns help developers structure their application in a particular, established way. There are many different design patterns that developers use in classes and for application design. Using a design pattern is helpful when working in larger groups, because there is a defined set of guidelines. Design patterns help ensure that every developer in the group can read a snippet of code and understand what is happening.
-
Behaviors conventions Behaviors are prewritten code snippets that can be instantly added to parts of a FLA file. The introduction of behaviors has added to the complexity of determining best practices in Flash, because the way some behaviors are added does not follow typical and ideal workflows. Many developers usually enter ActionScript either into one or several frames on the main Timeline or in external ActionScript files, which is a good practice to follow.
-
Find and replace Lets you search for strings and replace them in a FLA document. Script pinning Lets you pin multiple scripts from various objects and work with them simultaneously in the Actions panel. This works best with the Script navigator. Movie Explorer Lets you view and organize the contents of a FLA file, and select elements (including scripts) for further modification. Using behaviors Knowing when to use behaviors is the most important guideline.
-
Being consistent There are some guidelines for using behaviors; the main thing is consistency. If you add ActionScript to a FLA file, put code in the same locations where behaviors are added, and document how and where you add code. Note: If you are using a screen-based FLA file, see “Screens conventions” on page 107 for more information on best practices and screens. For example, if you place code on instances on the Stage, on the main Timeline, and in class files, you should examine your file structure.
-
Like the Behaviors guidelines, there are issues with how to organize and structure projects built with the screen-based authoring environment. Screens provide an intelligent and easy to use framework to control loading, persistence of data, and state using classes. Some developers build applications with all their ActionScript in a centralized location. Other designers and developers, usually newer to Flash, might use a more visual approach to writing a screens document.
-
If you use behaviors placed on screens (or other instances), remember to document the location on Frame 1 of the main Timeline. This is particularly important if you also place ActionScript on the Timeline. The following code is an example of the comment you might want to add to your FLA file: /* On Frame 1 of main Timeline. ActionScript is placed on individual screens and directly on instances in addition to the code on the Timeline (frame 1 of root screen). ...
-
Working with other structural elements A screen-based document, when published, is essentially a single movie clip on the first frame of a Timeline. This movie clip contains a few classes that compile into the SWF file. These classes add additional file size to the published SWF file compared with a nonscreen-based SWF file. The contents load into this first frame by default, which might cause problems in some applications.
-
Give users a certain amount of control (such as the ability to stop, pause, play, and resume the video, and control volume) over the video in a SWF file. For more information on using video in Flash, see “Working with Video” in Using Flash. Importing and embedding video You can embed video in a SWF file by importing it into your FLA document. You can import the video directly into the library, where it is stored as an embedded video.
-
Note: Remember to delete the FLV file from your Flash document and library if you intend to dynamically load the video into that document at runtime. Flash MX Professional includes an external FLV Exporter that compresses video from third-party video editing software such as QuickTime Pro and Adobe After Effects. The quality of the FLV file that is created using this tool is better than video exported directly from Flash.
-
Using Media components Media components are used to display FLV files or play MP3 files in a SWF file, and they only support these two file types. You can export each file format using a variety of software. For information on exporting the FLV format, see “Exporting FLV files” on page 111. Media components are easy to use, so you do not have to write ActionScript to dynamically load FLV files.
-
To dynamically load video using ActionScript: 1. Add a video object to the Stage by selecting New Video from the Library panel’s options menu. 2. Drag the video object on to the Stage, and resize the instance using the Property inspector to the same dimensions as your FLV file. 3. Enter an instance name of video1_video in the Property inspector. 4.
-
Optimize bitmaps as much as possible without overcompressing them. A 72-dpi resolution is optimal for the web. Compressing a bitmap image reduces file size, but compressing it too much compromises the quality of the graphic. Check that the settings for JPEG quality in the Publish Settings dialog box do not overcompress the image. If your image can be represented as a vector graphic, this is preferable in most cases.
-
If you use multiple components that do not share the same framework, they might add substantial file size to the SWF file. For example, the XMLConnector component adds 17K to the SWF file, and TextInput components add 24K to your document. If you add the ComboBox component, it adds 28K, because it is not part of either framework. Because the XMLConnector component uses data binding, the classes add 6K to the SWF file.
-
If you must restyle your components, you can improve efficiency in your application by using the Loader component. If you want to implement several styles in different components, you can place each component in its own SWF file. If you change styles on the Loader component and reload the SWF file, the components in the SWF file are recreated. When the component is recreated, the cache of styles is emptied, and the style for the component is reset and referenced again.
-
You cannot use any classes until the playhead reaches the frame you choose to load them into. Because components require classes for their functionality, you must load components after the Export frame for ActionScript 2.0 classes. If you export for Frame 3, you cannot use anything from those classes until the playhead reaches Frame 3 and loads the data. If you want to preload a file that uses components, you must preload the components in the SWF file.
-
Using System.useCodepage in your code forces the SWF file to use the system’s code page instead of Unicode. Only use this process in the following situations: when you are loading non-Unicode encoded text from an external location and when this text is encoded with the same code page as the user’s computer. If both these conditions are true, the text appears without a problem. If both of these conditions are not true, use Unicode and a Unicode escape sequence to format your text.
-
Optimizing ActionScript in Flash Player There are several ways that you can optimize your code for better SWF file performance, but remember that optimizing your code for Flash Player might reduce readability and consistency for code maintenance. Only practice optimize your code when necessary. Follow these guidelines to optimize your ActionScript for Flash Player: • Avoid calling a function multiple times from a loop. It is better to include the contents of a small function inside the loop.
-
Guidelines for Flash applications The best way to create different Flash applications depends on the application you create and the technology that you are using to build the application. There are guidelines that can help make the application process easier. There are also several decisions you need to make. This section describes some guidelines and suggestions for different types of projects and applications.
-
Collecting and formatting data Applications depend on user interaction with the SWF file. Frequently, it depends on the user entering data into forms, such as using combo boxes, buttons, text fields, sliders, and so on. You might create custom input devices, use the UI Components included with Flash, or download components. You might collect data in a series of pages (sometimes each one is a screen) that are contained within the single SWF file, which the user submits to the server.
-
You can also use escape and unescape for decoding. For a complete list of URL-encoded special characters, see www.macromedia.com/support/flash/ts/documents/url_encoding.htm. You must typically process information before you send it to the server, so it’s formatted in a way that the server understands. When the server receives the data, it can be manipulated in any number of ways and sent back to the SWF file in a format that it can accept, which can range from name/value pairs to complex objects.
-
There are some limitations when using web services with a SWF file, including the following: • Flash does not support web services with more than one defined port when using the WebServiceConnector component. • Flash does not support web services with more than one defined service when using the WebServiceConnector component. • • • • Flash does not support non-HTTP web services. Flash does not support web services on non-SOAP ports. Flash does not support REST web services.
-
You might receive data from a web service or from Flash Remoting. In both cases, you could receive complex data structures, such as arrays, objects, or record sets, which you must parse and bind appropriately. Using error handling and debugging An important part of application development is expecting and handling errors. No matter how simple your application might seem, there are always users who manage to enter data or interact with the SWF file in an unexpected way.
-
Using the MVC design pattern Many Flash developers implement the MVC (model, view, controller) design pattern when they build applications to separate the logic and data of the application from the user interface. This section defines how the design pattern works, and provides an overview of how and why you might use it for your Flash applications. The MVC design pattern is used to separate the information, output, and data processing in the application.
-
There are other reasons why MVC is valuable for some applications. An important reason to use the pattern is to separate data and logic from the user interface. By separating these parts of the process, you can have several different graphical interfaces that use the same model and unformatted data. This means that you can use your application with different Flash interfaces.
-
Using projects You can group multiple files into a single project file using the Project panel in Flash MX Professional 2004. This helps simplify application building, where managing related files could get complex and confusing. You can define a site for your work, create a Flash Project file (FLP), and then upload everything to the server so that a team can work on the project.
-
Authoring projects Authors on a Flash project do not change the project root, directory structure of the project, or the site. This includes adding, removing, or changing subdirectory names, or adding additional subdirectories to the project on their local computer. If individual authors change the site or project structure, the local files are out of sync with those on the server. This causes problems in the application, such as class path and missing file errors, and so on.
-
Creating accessible sites Flash Player uses Microsoft Active Accessibility (MSAA) to expose Flash content to screen readers. MSAA is a Windows-based technology that provides a standardized platform for information exchange between assistive technologies, such as screen readers, and other applications. Events (such as a change in the application) and objects are visible to screen readers by using MSAA.
-
Using screen readers A screen reader is software that lets your visitors hear a description of the contents of web pages. Text is read aloud using specially designed software. Obviously, a screen reader can only interpret textual content. However, any descriptions that you provide for the overall SWF file, movie clips, images, or other graphical content are also read aloud.
-
Controlling descriptions and repetition Designers and developers can assign descriptions for the animations, images, and graphics in a SWF file. Provide names for graphics so the screen reader can interpret them. If a graphic or animation does not communicate vital information to the SWF file (perhaps it is decorative or repetitive), or you outlined the element in the overall SWF file description, do not provide a separate description for that element.
-
Ordering, tabbing, and the keyboard The reading order and tabbing are possibly the two most important considerations for making accessible Flash websites. When you design an interface, the order that it appears on the page might not match the order in which the screen reader describes each instance. There are ways you can control and test reading order, as well as control tabbing in the SWF file. Controlling reading order Screen readers sometimes read assets in an unpredictable order.
-
Handling audio and animation Many SWF files contain audio, video, and narrations, because it is easy and robust to deliver this media using Flash. When you provide audio narrations or video that contains speech, it is important to provide captions for those users who cannot hear. You can use text fields in Flash, import video that contains captions, or even use an XML caption file. For information on using captions in Flash, see “Accessibility for hearing-impaired users” in Using Flash.
-
Thoroughly test component instances in your applications with a screen reader, because some components have problems when you use them with screen readers. In particular, test how the screen reader reads components aloud when the component is in an opened and closed state. Notice how the reader announces components when using key press actions to open, close, and select items in the component.
-
Advertising with Flash Many opportunities exist for creating interactive and engaging advertisements using SWF files. Macromedia recommends that you follow several guidelines when you produce Flash advertisements, based on standards set up by the Interactive Advertising Bureau (IAB). Using recommended dimensions It is recommended that you use the Interactive Advertising Bureau (IAB) guidelines to set dimensions for your Flash advertisements.
-
Use the GET command to pass data between an advertisement and a server, and do not use the POST command. For more information on GET and POST, see getURL() in Flash ActionScript Language Reference. Note: Remember to provide control to the user. If you add sound to an advertisement, also add a mute button. If you create a transparent Flash ad that hovers over a web page, always provide a button to close the advertisement for its entire duration.
-
And you would add the following code in your HTML: For more information on advanced tracking techniques, see the Rich Media Advertising Center at www.macromedia.com/devnet/rich_media_ads. To download the Rich Media Tracking Kit, which includes examples and documentation, see www.macromedia.com/resources/richmedia/tracking.
-
CHAPTER 4 Writing and Debugging Scripts Adding scripts to your Flash applications enables rich functionality. In Macromedia Flash MX 2004 and Macromedia Flash MX Professional 2004, you have two choices: • You can write scripts that are embedded in your Flash document (FLA file). To write embedded scripts, you use the Actions panel and attach your scripts to a button, movie clip, or frame in the Timeline (see “Controlling when ActionScript runs” on page 140).
-
Controlling when ActionScript runs When you write a script, you use the Actions panel to attach the script to a frame on a Timeline or to a button or movie clip on the Stage. Scripts attached to a frame run, or execute, when the playhead enters that frame.
-
To display the Actions panel: Do one of the following: • Select Window > Development Panels > Actions. • Press F9. (Flash Professional only) To display the Script window: Do one of the following: • To begin writing a new script, select File > New > ActionScript File. • To open an existing script, select File > Open, and then open an existing AS file. • To edit a script that is already open, click the document tab that shows the script’s name. (Document tabs are supported only in Microsoft Windows.
-
In the Actions panel, the Actions toolbox contains a Script navigator, which is a visual representation of the locations in the FLA file that have associated ActionScript; you can navigate through your FLA file to locate ActionScript code. If you click an item in the Script navigator, the script associated with that item appears in the Script pane, and the playhead moves to that position on the Timeline. If you double-click an item in the Script navigator, the script gets pinned (locked in place).
-
Managing scripts in a FLA file If you don’t centralize your code within a FLA file in one location, you can pin multiple scripts in the Actions panel to make it easier to move among them. In the following figure, the script associated with the current location on the Timeline is on Frame 1 of the layer named Cleanup. (The tab at the far left always follows your location along the Timeline.) That script is also pinned (it is shown as the rightmost tab).
-
To use keyboard shortcuts with pinned scripts: • You can use the following keyboard shortcuts to work with pinned scripts: Action Windows shortcut key Macintosh shortcut key Pin script Control+= (equal sign) Command+= Unpin script Control+- (minus sign) Command+- Move focus to tab on the right Control+Shift+. (period) Command+Shift+.
-
To set preferences for syntax coloring as you type, do one of the following: • Select Edit > Preferences, and specify Syntax coloring settings on the ActionScript tab. • In the Actions panel, select Preferences from the Options pop-up menu (at the upper right of the panel) and specify Syntax coloring settings on the ActionScript tab. • With the pointer focused in the Script pane, press Control-U (Windows) or Command-U (Macintosh).
-
Then you can type either of the following (the variable name followed by a period): my_array. my_cam. You will see code hints for the Array and Camera object, respectively, appear. For objects that appear on the Stage, use the suffix in the Instance Name text box in the Property inspector. For example, to display code hints for MovieClip objects, use the Property inspector to assign instance names with the suffix _mc to all MovieClip objects.
-
Object type Variable suffix XMLNode _xmlnode XMLSocket _xmlsocket For information on using code hints when they appear, see “Using code hints” on page 147. Using comments to trigger code hints You can also use ActionScript comments to specify an object’s class for code hinting. The following example tells ActionScript that the class of the instance theObject is Object, and so on.
-
To work with tooltip-style code hints: 1. Display the code hint by typing an opening parens [(] after an element that requires parentheses (such as a method name, a command such as if or do while, and so on). The code hint appears. Note: If a code hint doesn’t appear, make sure you haven’t disabled code hints on the ActionScript tab.
-
Note: If a code hint doesn’t appear, make sure you haven’t disabled code hints on the ActionScript tab. If you want to display code hints for a variable or object you created, make sure that you have named your variable or object correctly (see “Using suffixes to trigger code hints” on page 145) or that you have strictly typed your variable or object (see “Strictly typing objects to trigger code hints” on page 145). 2. To navigate through the code hints, use the Up and Down Arrow keys. 3.
-
If you want to learn (or be reminded) about which commands have Escape shortcut keys, you can show them next to elements in the Actions panel. To show or hide Escape shortcut keys: • From the View Options pop-up menu, enable or disable View Escape Shortcut Keys. Checking syntax and punctuation To determine whether the code you wrote performs as planned, you need to publish or test the file. However, you can do a quick check of your ActionScript code without leaving the FLA file.
-
Note: If you Check Syntax in external ActionScript 2.0 class files, the global class path will affect this process. Sometimes you will generate errors—even if the global class path is set correctly—because the compiler is not aware that this class is being compiled. For more information on compiling classes, see “Compiling and exporting classes” on page 272. To check for punctuation balance: 1. Click between braces ({}), brackets ([]), or parentheses [()] in your script. 2.
-
To use automatic indentation: • Automatic indentation is turned on by default. To turn it off, deselect Automatic indentation in ActionScript preferences. When automatic indentation is turned on, the text you type after ( or { is automatically indented according to the Tab size setting in ActionScript preferences. To indent another line, select the line and press Tab. To remove the indent, select the line and press Shift+Tab.
-
To select text encoding options for importing or exporting ActionScript files: 1. In the Preferences dialog box (Edit > Preferences), click the ActionScript tab. 2. Under Editing Options, do one or both of the following: ■ ■ For Open/Import, select UTF-8 to open or import using Unicode encoding, or select Default Encoding to open or import using the encoding form of the language currently used by your system.
-
The Debugger shows a hierarchical display list of movie clips currently loaded in Flash Player. Using the Debugger, you can display and modify variable and property values as the SWF file plays, and you can use breakpoints to stop the SWF file and step through ActionScript code line by line. You can use the Debugger in test mode with local files, or you can use it to test files on a web server in a remote location.
-
Debugging a SWF file from a remote location You can debug a remote SWF file using the stand-alone, ActiveX, or plug-in versions of Flash Player. When exporting a SWF file, you can enable debugging in your file and create a debugging password. If you don’t enable debugging, the Debugger will not activate. To ensure that only trusted users can run your SWF files in the Flash Debug Player, you can publish your file with a debugging password.
-
To activate the Debugger from a remote location: 1. Open the Flash authoring application. 2. In a browser or in the debug version of the stand-alone player, open the published SWF file from the remote location. The Remote Debug dialog box appears. If this dialog box doesn’t appear, Flash can’t find the SWD file. In this case, right-click (Windows) or Control-click (Macintosh) in the SWF file to display the context menu, and select Debugger. 3.
-
Displaying and modifying variables The Variables tab in the Debugger shows the names and values of any global and Timeline variables in the SWF file selected in the display list. If you change the value of a variable on the Variables tab, you can see the change reflected in the SWF file while it runs. For example, to test collision detection in a game, you can enter the variable value to position a ball in the correct location next to a wall.
-
Using the Watch list To monitor a set of critical variables in a manageable way, you can mark variables to appear in the Watch list. The Watch list shows the absolute path to the variable and the value. You can also enter a new variable value in the Watch list the same way as in the Variables tab. The Watch list can show only variables and properties that can be accessed by using an absolute target path, such as _global, _root.
-
To display a movie clip’s properties in the Debugger: 1. Select a movie clip from the display list. 2. Click the Properties tab in the Debugger. To modify a property value: • Double-click the value, and enter a new value. The value cannot be an expression. For example, you can enter 50 or "clearwater", but you cannot enter x + 50. The value can be a string (any value surrounded by quotation marks [""]), a number, or a Boolean value (true or false).
-
Caution: If you set breakpoints in the Actions panel and press the Auto Format button, you might notice that some breakpoints are no longer in the correct location. ActionScript might be moved to a different line when your code is formatted because sometimes empty lines are removed. It might be necessary to check and modify your breakpoints after you click Auto Format, or to auto format your scripts before setting breakpoints.
-
When you click the button, the breakpoint is reached and Flash Player pauses. You can now step in to bring the Debugger to the first line of myFunction() wherever it is defined in the document. You can also step through or out of the function. As you step through lines of code, the values of variables and properties change in the Watch list and in the Variables, Locals, and Properties tabs. A yellow arrow on the left side of the Debugger’s code view indicates the line at which the Debugger stopped.
-
Continue leaves the line at which the player is stopped and continues playing until a breakpoint is reached. Stop Debugging makes the Debugger inactive but continues to play the SWF file in Flash Player. Using the Output panel In test mode, the Output panel shows information to help you troubleshoot your SWF file. Some information (such as syntax errors) appear automatically. You can show other information by using the List Objects and List Variables commands.
-
Menu item What it does Print Shows the Print dialog box, which lets you print the current contents of the Output panel to an installed printer or installed programs such as Flash Paper or Acrobat. Filter level Lets you select two possible levels of output: None or Verbose. Selecting None suppresses all output sent to the browser. Maximize Panel Maximizes the Output panel (when it is docked). Close Panel Closes the Output panel and clears the contents of the panel.
-
Listing a SWF file’s variables In test mode, the List Variables command shows a list of all the variables currently in the SWF file. This is especially useful for finding the correct variable target path and variable name. Unlike the Debugger, the list does not update automatically as the SWF file plays; you must select the List Variables command each time you want to send the information to the Output panel. The List Variables command also shows global variables declared with the _global identifier.
-
• Color properties appear as hexadecimal numbers (0x00FF00). • The properties appear in the following order: variable, text, htmlText, html, textWidth, textHeight, maxChars, borderColor, backgroundColor, textColor, border, background, wordWrap, password, multiline, selectable, scroll, hscroll, maxscroll, maxhscroll, bottomScroll, type, embedFonts, restrict, length, tabIndex, autoSize. The List Objects command in the Debug menu (during test mode) lists TextField objects.
-
Chapter 4: Writing and Debugging Scripts
-
CHAPTER 5 Handling Events An event is a software or hardware occurrence that requires a response from a Macromedia Flash application. For example, 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 is generated automatically by Flash Player, 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.
-
The following ActionScript classes define event handlers: “Button class”, “ContextMenu class”, “ContextMenuItem class”, “Key class”, “LoadVars class”, “LocalConnection class”, “Mouse class”, “MovieClip class”, “MovieClipLoader class”, “Selection class”, “SharedObject class”, “Sound class”, “Stage class”, “TextField class”, “XML class”, and “XMLSocket class”. For more information about the event handlers they provide, see each class entry in Flash ActionScript Language Reference.
-
For example, the following code inserts some text into a text field that no longer has keyboard focus: this.createTextField("my_txt", 99, 10, 10, 200, 20); my_txt.border = true; my_txt.type = "input"; this.createTextField("myOther_txt", 100, 10, 50, 200, 20); myOther_txt.border = true; myOther_txt.type = "input"; myOther_txt.onSetFocus = function(my_txt:TextField) { my_txt.
-
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.
-
To create a simple focus manager with event listeners: 1. Using the Text tool, create a text field on the Stage. 2. Select the text field and, in the Property inspector, select Input from the Text Type pop-up menu, and select the Show Border Around Text option. 3. Create another input text field below the first one. Make sure the Show Border Around Text option is not selected for this text field. You can continue to create input text fields. 4.
-
Note: Do not confuse button and movie clip event handlers with component events, such as SimpleButton.click, UIObject.hide, and UIObject.reveal, which must be attached to component instances and are discussed in Using Components Help. You can attach onClipEvent() and on() only to movie clip instances that have been placed on the Stage during authoring. You cannot attach onClipEvent() or on() to movie clip instances that are created at runtime (using the attachMovie() method, for example).
-
Using on() and onClipEvent() with event handler methods You can, in some cases, use different techniques to handle events without conflict. Using on() and onClipEvent() doesn’t conflict with using event handler methods that you define. For example, suppose you have a button in a SWF file; the button can have an on(press) handler that tells the SWF file to play, and the same button can have an onPress method, for which you define a function that tells an object on the Stage to rotate.
-
Event handler scope The scope, or context, of variables and commands that you declare and execute within an event handler depends on the type of event handler you use: event handlers or event listeners, or on() and onClipEvent() handlers. If you’re defining an event handler in a new ActionScript 2.0 class, the scope also depends on how you define the event handler. This section contains both ActionScript 1 and ActionScript 2.0 examples.
-
When attached to a button object, the play() function applies to the Timeline that contains the button—that is, the button’s parent Timeline. But when the on(press) handler is attached to a movie clip object, the play() function call applies to the movie clip that bears the handler. If you attach the following code to a movie clip, it plays the parent Timeline: // Attached to movie clip on(press) { _parent.
-
This code cannot work correctly because there is a problem involving scope with the event handlers, and what this refers to is confused between the onLoad event handler and the class. The behavior that you might expect in this example is that the onLoadVarsDone() method will be invoked in the scope of the Loader object; but it is invoked in the scope of the LoadVars object because the method has been extracted from the Loader object and grafted onto the LoadVars object.
-
Within an on() handler attached to a button, this refers to the Timeline that contains the button, as shown in the following code: // Attached to button on main Timeline on(press) { trace(this); // displays '_level0' } Scope of the this keyword 177
-
Chapter 5: Handling Events
-
CHAPTER 6 Creating Interaction with ActionScript In simple animations, Macromedia Flash Player plays the scenes and frames of a SWF file sequentially. In an interactive SWF file, your audience uses the keyboard and mouse to jump to different parts of a SWF file, move objects, enter information in forms, and perform many other interactive operations. You use ActionScript to create scripts that tell Flash Player what action to perform when an event occurs.
-
Controlling SWF file playback The following ActionScript functions let you control the playhead in the Timeline and load a new web page into a browser window: • The gotoAndPlay() and gotoAndStop() functions send the playhead to a frame or scene. These are global functions that you can call from any script. You can also use the and MovieClip.gotoAndStop() methods to navigate the Timeline of a specific movie clip object. MovieClip.gotoAndPlay() • The play() and stop() actions play and stop movies.
-
// Plays the Timeline that contains the button play(); } This same on() event handler code produces a different result when attached to a movie clip object rather than a button. When attached to a button object, statements made within an on() handler are applied to the Timeline that contains the button, by default. However, when attached to a movie clip object, statements made within an on() handler are applied to the movie clip to which the on() handler is attached.
-
The following code then loads addUser.cfm into a blank browser window and passes to the CFM page variables_mc.name and variables_mc.age in the POST header: variables_mc.getURL("addUser.cfm", "_blank", "POST"); For more information, see getURL() in Flash ActionScript Language Reference.
-
The Mouse.hide() method hides the pointer when the movie clip first appears on the Stage; the onMouseMove function positions the custom pointer at the same place as the pointer and calls updateAfterEvent whenever the user moves the mouse. The updateAfterEvent function immediately refreshes the screen after the specified event occurs, rather than when the next frame is drawn, which is the default behavior.
-
The following procedure shows several ways to get the pointer position within the main Timeline or within a movie clip. To get the current pointer position: 1. Create two dynamic text fields, and name them box1_txt and box2_txt. 2. Add labels for the text boxes: X position and Y position, respectively. 3. Select Window > Development Panels > Actions to open the Actions panel if it is not already open. 4.
-
To decide which keys to use and determine their virtual key codes, use one of the following approaches: • See the list of key codes in Appendix C, “Keyboard Keys and Key Code Values,” on page 313. See the list of key codes in Appendix C, “Keyboard Keys and Key Code Values,” in ActionScript Dictionary Help. • Use a Key class constant. (In the Actions toolbox, click Built-in Classes > Movie > Key > Constants.
-
The following procedure shows how to capture keypresses to move a movie clip up, down, left, or right on the Stage, depending on which corresponding arrow key (up, down, left, or right) is pressed. The movie clip is confined to an arbitrary area that is 400 pixels wide and 300 pixels high. Also, a text field shows the name of the pressed key. To create a keyboard-activated movie clip: 1. On the Stage, create a movie clip that can move in response to keyboard arrow activity.
-
display_txt.text = "Right"; } else if (Key.isDown(Key.UP)) { this._y = Math.max(this._y-distance, 0); display_txt.text = "Up"; } else if (Key.isDown(Key.DOWN)) { this._y = Math.min(this._y+distance, 400-this._height); display_txt.text = "Down"; } }; 8. Select Control > Test Movie to test the file. For more information about the methods of the Color class, see the Color class entry in ActionScript Dictionary Help.
-
5. To create a Color object that targets the car_mc movie clip, add the following code to the Actions panel: var myColor_color:Color = new Color(car_mc); 6. To make the red button change the color of the carColor movie clip to red, add the following code to the Actions panel: red_btn.onRelease = function() { car_color.setRGB(0xFF0000); }; The hexadecimal value 0xFF0000 is red. 7.
-
Creating sound controls You use the built-in Sound class to control sounds in a SWF file. To use the methods of the Sound class, you must first create a Sound object. Then you can use the attachSound() method to insert a sound from the library into a SWF file while the SWF file is running. When the user releases the Play button, a song plays through the speaker. The Sound class’s setVolume() method controls the volume, and the setPan() method adjusts the left and right balance of a sound.
-
The following procedures show how to create sound controls similar to the ones shown in the figure. To attach a sound to a Timeline: 1. Select File > Import to import a sound. 2. Select the sound in the library, right-click (Windows) or Control-click (Macintosh), and select Linkage. 3. Select Export for ActionScript and Export in First Frame; then give it the identifier a_thousand_ways. 4. Add a button to the Stage and name it play_btn. 5. Add a button to the Stage and name it stop_btn. 6.
-
6. Enter the following event handlers: slider_mc.knob_btn.onPress = function() { startDrag(this._parent, false, this._parent.left, this._parent.top, this._parent.right, this._parent.bottom); }; slider_mc.knob_btn.onRelease = function() { stopDrag(); }; slider_mc.onEnterFrame = function() { this._parent.song.setVolume(this._x-this.left); this._parent.volume_txt.text = this._x-this.left; }; The startDrag() parameters left, top, right, and bottom are variables set in a clip action. 7.
-
Detecting collisions The hitTest() method of the MovieClip class detects collisions in a SWF file. It checks to see if an object has collided with a movie clip and returns a Boolean value (true or false). There are two cases in which you would want to know whether a collision has occurred: to test if the user has arrived at a certain static area on the Stage or to determine when one movie clip has reached another. With hitTest(), you can determine these results.
-
To detect a collision between a movie clip and a point on the Stage: 1. Create a new movie clip on the Stage, and enter box_mc as the instance name in the Property inspector. 2. Select the first frame on Layer 1 in the Timeline. 3. Select Window > Development Panels > Actions to open the Actions panel, if it is not already open. 4. Add the following code in the Actions panel: this.createTextField("status_txt", 999, 0, 0, 100, 22); status_txt.border = true; box_mc.onEnterFrame = function() { status_txt.
-
Creating a simple line drawing tool You can use methods of the MovieClip class to draw lines and fills on the Stage as the SWF file plays. This lets you create drawing tools for users and draw shapes in the SWF file in response to events. The drawing methods are beginFill(), beginGradientFill(), clear(), curveTo(), endFill(), lineTo(), lineStyle(), and moveTo(). You can apply these methods to any movie clip instance (for example, myClip.lineTo()) or to a level (_level0.curveTo()).
-
mouseListener.onMouseUp = function() { isDrawing = false; }; Mouse.addListener(mouseListener); 5. Select Control > Test Movie to test the movie. Click and drag your pointer to draw a line on the Stage. Click the button to erase what you’ve drawn. Deconstructing a sample script In the sample SWF file zapper.swf (which you can view in Using Flash Help), when a user drags the bug to the electrical outlet, the bug falls and the outlet shakes.
-
if (zapped) { bug_mc._y += 25; } }; The bug’s instance name is bug_mc, and the outlet’s instance name is zapper_mc. In the script, the bug is referred to as this because the script is attached to the bug and the reserved word this refers to the object that contains it. There are event handlers with several different events: onRelease, onPress, and enterFrame. The event handlers are defined on Frame 1 after the SWF file loads.
-
CHAPTER 7 Using the Built-In Classes In addition to the ActionScript core language elements and constructs (for and while loops, for example) and primitive data types (numbers, strings, and arrays) described earlier in this manual (see “ActionScript Basics” on page 23), ActionScript also provides several built-in classes (complex data types). These classes provide a variety of scripting features and functionality.
-
For more information, see the following topics: • • • • “Creating a new object” on page 198 “Accessing object properties” on page 198 “Calling object methods” on page 198 “About class (static) members” on page 199 Creating a new object To create an instance of an ActionScript class, use the new operator to invoke the class’s constructor function. The constructor function always has the same name as the class, and returns an instance of the class, which you typically assign to a variable.
-
About class (static) members Some built-in ActionScript classes have class members (or static members). Class members (properties and methods) are accessed or invoked on the class name, not on an instance of the class. Therefore, you don’t create an instance of the class to use those properties and methods. For example, all the properties of the Math class are static. The following code invokes the max() method of the Math class to determine the larger of two numbers: var largerNumber:Number = Math.
-
Class Description Math The Math class provides convenient access to common mathematical constants and provides several common mathematical functions. All the properties and methods of the Math class are static and must be called with the syntax Math.method(parameter) or Math.constant. See “Math class”in Flash ActionScript Language Reference. Number The Number class is a wrapper for the primitive number data type. See “Number class”in Flash ActionScript Language Reference.
-
Media classes The media classes provide playback control of sound and video in a SWF file as well as access to the user’s microphone and camera, if they are installed. These classes are located in the Built-in Classes > Media directory in the Actions toolbox. Class Description Camera The Camera class provides access to the user’s camera, if one is installed. When used with Flash Communication Server MX, your SWF file can capture, broadcast, and record images and video from a user’s camera.
-
Movie classes The movie classes provide control over most visual elements in a SWF file, including movie clips, text fields, and buttons. The movie classes are located in the Actions toolbox in the Built-in Classes > Movie directory. 202 Class Description Accessibility The Accessibility class manages communication between SWF files and screen reader applications.
-
Class Description MovieClipLoader The MovieClipLoader class lets you track the download progress of SWF and JPEG files using an event listener mechanism. See the “MovieClipLoader class” in Flash ActionScript Language Reference and “Preloading SWF and JPEG files” on page 301. PrintJob The PrintJob class lets you print content from a SWF file, including content that is rendered dynamically and multi-page documents.
-
These classes are located in the Built-in Classes > Client/Server folder in the Actions toolbox. Class Description LoadVars The LoadVars class is an alternative to the MovieClip.loadVariables() action for transferring variables between a SWF file and a server in namevalue pairs. See “LoadVars class” and “Using the LoadVars class” in Flash ActionScript Language Reference.
-
CHAPTER 8 Working with Movie Clips Movie clips are self-contained SWF files that run independently of each other and the Timeline that contains them. For example, if the main Timeline has only one frame and a movie clip in that frame has ten frames, each frame in the movie clip plays when you play the main SWF file. A movie clip can, in turn, contain other movie clips, or nested clips. Movie clips nested in this way have a hierarchical relationship, where the parent clip contains one or more child clips.
-
When a function and a method offer similar behaviors, you can select to control movie clips by using either one. The choice depends on your preference and your familiarity with writing scripts in ActionScript. Whether you use a function or a method, the target Timeline must be loaded in Flash Player when the function or method is called. To use a method, invoke it by using the target path of the instance name, a dot (.
-
The with statement takes a movie clip as a parameter. The object you specify is added to the end of the current target path. All actions nested inside a with statement are carried out inside the new target path, or scope. For example, in the following script, the with statement is passed the object donut.hole to change the properties of hole: with (donut.
-
• Develop a branching interface with links that lets the user select among several SWF files that are used to display a site’s content. • Build a navigation interface with navigation controls in level 0 that loads content into other levels. Loading content into levels helps produce smoother transitions between pages of content than loading new HTML pages in a browser. For more information on loading movies, see “Loading external SWF and JPEG files” on page 296.
-
This step ensures that any references to _root in contents.swf—or any SWF file loaded into target_mc—will refer to its own Timeline, not the actual root Timeline of container.swf. Now when you click the button, "Tim" appears. Equivalently, the author of contents.swf could add the following code to its main Timeline: // Added to Frame 1 in contents.swf: this._lockroot = true; This would ensure that no matter where contents.
-
In addition, you can write statements that get the value of a movie clip property. For example, the following statement gets the value of the _xmouse property on the current level’s Timeline and sets the _x property of the my_mc instance to that value: this.onEnterFrame = function() { my_mc._x = this._xmouse; }; This is equivalent to the following code, which uses the getProperty() function: this.onEnterFrame = function() { my_mc.
-
Creating movie clips at runtime Not only can you create movie clip instances in the Flash authoring environment, you can also create movie clip instances at runtime in the following ways: • “Creating an empty movie clip” on page 211 • “Duplicating or removing a movie clip” on page 212 • “Attaching a movie clip symbol to the Stage” on page 212 Each movie clip instance you create at runtime must have an instance name and a depth (stacking, or z-order) value.
-
For more information, see MovieClip.createEmptyMovieClip() in Flash ActionScript Language Reference. Duplicating or removing a movie clip To duplicate or remove movie clip instances, use the duplicateMovieClip() or global functions, or the MovieClip class methods of the same name. The duplicateMovieClip() method creates a new instance of an existing movie clip instance, assigns it a new instance name, and gives it a depth, or z-order.
-
7. If you don’t want the movie clip to load before the first frame, deselect the Export in First Frame option. If you deselect this option, place an instance of the movie clip on the frame of the Timeline where you want it to be available. For example, if the script you’re writing doesn’t reference the movie clip until Frame 10, then place an instance of the symbol at or before Frame 10 on the Timeline. 8. Click OK.
-
To populate a dynamically created movie clip with parameters from a specified object: Do one of the following: • Use the following syntax with attachMovie(): myMovieClip.attachMovie(idName, newName, depth [, initObject]) • Use the following syntax with duplicateMovie(): myMovieClip.duplicateMovie(idName, newName, depth [, initObject]) The initObject parameter specifies the name of the object whose parameters you want to use to populate the dynamically created movie clip.
-
Managing movie clip depths Every movie clip has its own z-order space that determines how objects overlap within its parent SWF file or movie clip. Every movie clip has an associated depth value, which determines if it will render in front of or behind other movie clips in the same movie clip Timeline. When you create a movie clip at runtime using MovieClip.attachMovie(), MovieClip.duplicateMovieClip(), or MovieClip.createEmptyMovieClip(), you always specify a depth for the new clip as a method parameter.
-
In this case, the variable named nextDepth contains the value 11 because that’s the next highest available depth for the movie clip edit_mc. To obtain the current highest occupied depth, subtract 1 from the value returned by as shown in the next section. getNextHighestDepth(), Determining the instance at a particular depth To determine the instance at a particular depth, use MovieClip.getInstanceAtDepth(). This method returns a reference to the MovieClip instance at the specified depth.
-
You can use movie clips with drawing methods as masks; however, as with all movie clip masks, strokes are ignored. To draw a shape: 1. Use MovieClip.createEmptyMovieClip() to create an empty movie clip on the Stage. The new movie clip is a child of an existing movie clip or of the main Timeline, as shown in the following example: this.createEmptyMovieClip ("triangle_mc", 1); 2. Use the empty movie clip to call drawing methods.
-
About masking device fonts You can use a movie clip to mask text that is set in a device font. In order for a movie clip mask on a device font to work properly, the user must have Flash Player 6 (6.0.40.0) or later. When you use a movie clip to mask text set in a device font, the rectangular bounding box of the mask is used as the masking shape.
-
} } 4. Save the document as MoveRight.as in the BallTest directory. To assign the class to a movie clip symbol: 1. In Flash, select File > New, select Flash Document from the list of file types, and click OK. 2. Using the Oval tool, draw a circle on the Stage. 3. Select the circle, and select Modify > Convert to Symbol. 4. In the Convert to Symbol dialog box, select Movie Clip as the symbol’s behavior, and enter ball_mc in the Name text box. 5.
-
Assuming this class is assigned to a symbol with a linkage identifier of Ball, the following code creates two new instances of the symbol on the root Timeline of the SWF file. The first instance, named ball50_mc, moves 50 pixels each time it is clicked; the second, named ball125_mc, moves 125 pixels each time its clicked. this.attachMovie("Ball", "ball50_mc", 10, {distance:50}); this.
-
CHAPTER 9 Working with Text A dynamic or input text field is a TextField object (an instance of the TextField class). When you create a text field, you can assign it an instance name in the Property inspector. You can use the instance name in ActionScript statements to set, change, and format the text field and its content using the TextField and TextFormat classes.
-
To control a dynamic or input text field using ActionScript, you must assign it an instance name in the Property inspector. You can then reference the text field with the instance name, and use the methods and properties of the TextField class to control the contents or basic appearance of the text field. You can also create TextField objects at runtime, and assign them instance names, using the method. For more information, see “Creating text fields at runtime” on page 223. MovieClip.
-
However, you can’t use the variable name mytextVar to set the text field’s text property. You have to use the instance name, as shown in the following code: //This won’t work mytextVar.text = "A text field variable is not an object reference"; //For input text field with instance name "myField", this will work myField.text = "This sets the text property of the myField object"; In general, use the TextField.
-
Using the TextFormat class You can use the ActionScript TextFormat class to set formatting properties of a text field. The TextFormat class incorporates character and paragraph formatting information. Character formatting information describes the appearance of individual characters: font name, point size, color, and an associated URL. Paragraph formatting information describes the appearance of a paragraph: left margin, right margin, indentation of the first line, and left, right, or center alignment.
-
5. Apply the TextFormat object to the text field you created in step 1 using TextField.setTextFormat(): myText_txt.setTextFormat(txtfmt); This version of setTextFormat() applies the specified formatting to the entire text field. There are two other versions of this method that let you apply formatting to individual characters or groups of characters. For example, the following code applies bold, italic, 24point formatting to the first three characters you entered in the text field: myText_txt.
-
Getting text metric information You can use the TextFormat.getTextExtent() method to obtain detailed text measurements for a text string that has specific formatting. For example, suppose you need to create, at runtime, a new TextField object containing an arbitrary amount of text that is formatted with a 24-point, bold, Arial font, and a 5-pixel indent. You need to determine how wide or high the new TextField object must be to display all the text.
-
• • • • • “Using style classes” on page 231 “Styling built-in HTML tags” on page 231 “An example of using styles with HTML” on page 232 “Using styles to define new tags” on page 234 “An example of using styles with XML” on page 235 Supported CSS properties Flash Player supports a subset of properties in the original CSS1 specification (www.w3.org/TR/ REC-CSS1). The following table shows the supported CSS properties and values as well as their corresponding ActionScript property names.
-
Creating a style sheet object CSS are represented in ActionScript by the TextField.StyleSheet class. This class is available only for SWF files that target Flash Player 7 or later. To create a style sheet object, call the TextField.StyleSheet class’s constructor function: var newStyle = new TextField.StyleSheet(); To add styles to a style sheet object, you can either load an external CSS file into the object or define the styles in ActionScript.
-
7. Add the following code to the Actions panel: var styles = new TextField.StyleSheet(); styles.load("styles.css"); styles.onLoad = function(ok) { if (ok) { // display style names trace(this.getStyleNames()); } else { trace("Error loading CSS file."); } }; Note: In the previous code snippet, this in this.getStyleNames() refers to the styles object you constructed in the first line of ActionScript. 8. Save the FLA file to the same directory that contains styles.css. 9. Test the movie (Control > Test Movie).
-
Applying styles to a TextField object To apply a style sheet object to a TextField object, you assign the style sheet object to the text field’s styleSheet property. textObj_txt.styleSheet = styleSheetObj; Note: Do not confuse the TextField.styleSheet property with the TextField.StyleSheet class. The capitalization indicates the difference.
-
myTextArea.html = true; var myVars:LoadVars = new LoadVars(); //var styles = new TextField.StyleSheet(); // Load text to display and define onLoad handler myVars.load("myText.htm"); myVars.onData = function(content) { _root.myTextArea.text = content; }; Combining styles CSS styles in Flash Player are additive; that is, when styles are nested, each level of nesting can contribute style information, which is added together to result in the final formatting.
-
p { font-family: Arial,Helvetica,sans-serif; font-size: 12px; display: inline; } The following table shows which built-in HTML tags can be styled and how each style is applied: Style name How the style is applied p Affects all
tags. body Affects all
tags. The p style, if specified, takes precedence over the body style. li Affects all - bullet tags. a Affects all anchor tags. a:link Affects all anchor tags. This style is applied after any a style.
-
font-family: Arial,Helvetica,sans-serif; font-size: 18px; font-weight: bold; display: block; } .byline { color: #666600; font-style: italic; font-weight: bold; display: inline; } This style sheet defines styles for two built-in HTML tags (
and ) that will be applied to all instances of those tags. It also defines two style classes (.headline and .byline) that will be applied to specific paragraphs and text spans. 3. Save the file as html_styles.css. 4.
-
styles.load(css_url); styles.onLoad = function(ok) { if (ok) { // If the style sheet loaded without error, // then assign it to the text object, // and assign the HTML text to the text field. news_txt.styleSheet = styles; news_txt.text = storyText; } }; Note: In this ActionScript, you are loading the text from an external file. For information on loading external data, see Chapter 12, “Working with External Media,” on page 295. 11. Save the file as news_html.
-
An example of using styles with XML In this section, you can create a FLA file that has XML-formatted text. You’ll create a style sheet using ActionScript, rather than importing styles from a CSS file as shown in “An example of using styles with HTML” on page 232 To format XML with a style sheet: 1. In Flash, create a FLA file. 2. Using the Text tool, create a text field approximately 400 pixels wide and 300 pixels high. 3. Open the Property inspector (Window > Properties), and select the text field. 4.
-
7. To create the XML text to assign to the text field, open a text editor and enter the following text into a new document: Flash Player now supports CSSSan Francisco, CA--Macromedia Inc. announced today a new version of Flash Player that supports Cascading Style Sheets (CSS) text styles. For more information, visit the PAGE 237
For more information on HTML-formatted text, see the following topics: • “Overview of using HTML-formatted text” on page 237 • “Supported HTML tags” on page 237 • “Embedding images, SWF files, and movie clips in text fields” on page 242 Overview of using HTML-formatted text To use HTML in a text field, you must enable the text field’s HTML formatting either by selecting the Render Text as HTML option in the Property inspector or by setting the text field’s html property to true.
-
For example, the following HTML code creates the link “Go home,” which opens www.macromedia.com in a new browser window: urlText_txt.htmlText = “Go home”; You can use the special asfunction protocol to cause the link to execute an ActionScript function in a SWF file instead of opening a URL. For more information on the asfunction protocol, see asfunction in Flash ActionScript Language Reference.
-
• size Specifies the size of the font, in pixels, as shown in the following example: myText_txt.htmlText = "This is blue, 24point text"; You can also use relative point sizes instead of a pixel size, such as +2 or -4. Image tag (
) The
tag lets you embed external JPEG files, SWF files, and movie clips inside text fields and TextArea component instances. Text automatically flows around images you embed in text fields or components.
-
Italic tag () The tag displays the tagged text in italics, as shown in the following code: That is very interesting. This code example would render as follows: That is very interesting. An italic typeface must be available for the font used.
-
Span tag () The tag is available only for use with CSS text styles. (For more information, see “Formatting text with Cascading Style Sheets” on page 226.) It supports the following attribute: • Specifies a CSS style class defined by an TextField.StyleSheet object. For more information on creating text style classes, see “Using style classes” on page 231.
-
4. Open the Actions panel (Window > Development Panels > Actions), and enter the following code in the Actions panel: //Creates column headers, formatted in bold, separated by tabs var rowHeaders = "Name\tAge\tDepartment"; //Creates rows with data var row_1 = "Tim\t32\tFinance"; var row_2 = "Edwin\t46\tMarketing"; //Sets two tabstops, to 50 and 100 points table_txt.htmlText = ""; table_txt.htmlText += rowHeaders; table_txt.htmlText += row_1; table_txt.
-
Embedding movie clip symbols To embed a movie clip symbol in a text field, you specify the symbol’s linkage identifier for the
tag’s src attribute. (For information on defining a linkage identifier, see “Attaching a movie clip symbol to the Stage” on page 212.) For example, the following code inserts a movie clip symbol with the linkage identifier symbol_ID into a dynamic text field with the instance name textField_txt. textField_txt.
-
Making hypertext links out of embedded media To make a hypertext link out of an embedded JPEG file, SWF file, or movie clip, enclose the
tag in an tag: textField.htmlText = "Click the image to return home
"; When the mouse pointer is over an image, SWF file, or movie clip that is enclosed by tags, the pointer turns into a “pointing hand” icon, the same as it does with standard hypertext links.
-
2. Create an Up button and a Down button, or select Window > Other Panels > Common Libraries > Buttons, and drag buttons to the Stage. You will use these buttons to scroll the text up and down. 3. Select the Down button on the Stage and type down_btn into the Instance Name text box. 4. Select the Up button on the Stage, and type up_btn into the Instance Name text box. 5.
-
Chapter 9: Working with Text
-
CHAPTER 10 Creating Custom Classes with ActionScript 2.0 ActionScript 2.0 is a restructuring of the ActionScript language that provides several powerful new programming features found in other programming languages, such as Java. ActionScript 2.0 encourages program structures that are reusable, scalable, robust, and maintainable. It also decreases development time by providing users thorough coding assistance and debugging information. ActionScript 2.
-
This section contains code examples that you can use to become familiar with creating classes in ActionScript 2.0. If you’re not familiar with ActionScript 2.0 scripting, see Chapter 2, “ActionScript Basics,” on page 23 and Chapter 3, “Using Best Practices,” on page 65. Principles of object-oriented programming This section provides a brief introduction to principles involved in developing object-oriented programs.
-
Inheritance One of the primary benefits of object-oriented programming is that you can create subclasses of a class; the subclass then inherits all the properties and methods of the superclass. The subclass typically defines additional methods and properties, or extends the superclass. Subclasses can also override (provide their own definitions for) methods inherited from a superclass. For example, you might create a Mammal class that defines certain properties and behaviors common to all mammals.
-
Encapsulation is why ActionScript 2.0 includes, for example, member access control, so details of the implementation can be made private and invisible to code outside an object. The code outside the object is forced to interact with the object’s programming interface rather than with the implementation details.
-
Creating a class file To create a class, you must first create an external ActionScript (AS) file. Classes (and interfaces) can be defined only in external script files. You can’t define a class in a script attached to a frame or button in a Flash document (FLA file). To create an external AS file, use the ActionScript editor included with Flash Professional or your preferred code or text editor.
-
6. To create the properties for the Person class, use the var keyword to define two variables named age and name, as shown in the following example: class Person { var age:Number; var name:String; } Tip: By convention, class properties are defined at the top of the class body, which makes the code easier to understand, but this isn’t required. The colon syntax (var age:Number and var name:String) used in the variable declarations is an example of strict data typing.
-
// Constructor function function Person (myName:String, myAge:Number) { this.name = myName; this.age = myAge; } // Method to return property values function getInfo():String { return("Hello, my name is " + this.name + " and I’m " + this.age + " years old."); } } This code is the completed code for this class. The return value of the getInfo() function is strictly typed (optional, but recommended) as a string. 9. Save the file.
-
To create an instance of the Person class in a Flash document: 1. In Flash, select File > New, select Flash Document from the list of document types, and click OK. 2. Save the file as createPerson.fla in the PersonFiles directory you created. By saving your FLA and AS files in the same directory, you can refer to the class using the fully qualified class name in step 6. 3. Select Layer 1 in the Timeline, and open the Actions panel (Window > Development Panels > Actions). 4.
-
All AS class files that you create must be saved in one of the designated classpath directories— directories where Flash looks for class definitions when compiling scripts—that is, in the same directory where the FLA file that refers to the class is stored. (See “Understanding the classpath” on page 268.) If you are creating multiple custom classes, use packages to organize your class files. A package is a directory that contains one or more class files and resides in a designated classpath directory.
-
The this keyword is not required in ActionScript 2.0 class definitions because the compiler resolves the reference and adds it into the bytecode. However, using this can improve your code’s readability. See “Using the this keyword” on page 96. Creating properties and methods A class’s members consist of properties (variable declarations) and methods (function definitions).
-
} } Private members (properties and methods) are accessible only to the class that defines those members and to subclasses of that original class. Instances of the original class, or instances of subclasses of that class, cannot access privately declared properties and methods; that is, private members are accessible only within class definitions; not at the instance level. For example, you could create a subclass of LoginClass called NewLoginClass.
-
function myFunc():String { return "Hello world"; } } This rule applies only to instance variables (variables that are copied into each instance of a class), not class variables (variables that belong to the class). For more information about these kinds of variables, see “Instance and class members” on page 263.
-
If you don’t place a call to super() in the constructor function of a subclass, the compiler automatically generates a call to the constructor of its immediate superclass with no parameters as the first statement of the function. If the superclass doesn’t have a constructor, the compiler creates an empty constructor function and then generates a call to it from the subclass.
-
Now, instances of the Person class can add and access properties and methods that aren’t defined in the original class, as shown in the following example: var a_person:Person2 = new Person2(); a_person.hairColor = "blue";//no compiler error because class is dynamic trace(a_person.hairColor); Subclasses of dynamic classes are also dynamic, with one exception. Subclasses of the built-in MovieClip class are not dynamic by default, even though the MovieClip class itself is dynamic.
-
// In Shapes/Circle.as: class Shapes.Circle {} // In Shapes/Triangle.as: class Shapes.Triangle {} To reference a class that resides in a package directory, you can either specify its fully qualified class name or import the package by using the import statement (see the following section). For more information about the naming conventions for packages, see “Packages” on page 73 in Chapter 3, “Using Best Practices.
-
For example, the following code declares an interface named MyInterface that contains two methods, method_1() and method_2(). The first method, method_1(), has no parameters and specifies a return type of Void (meaning it does not return a value). The second method, method_2(), has a single parameter of type String, and specifies a return type of Boolean.
-
In another script, such as the following code, where you create an instance of the Box class, you could declare a variable to be of the Movable type: import Box; var newBox:Movable = new Box(); At runtime, in Flash Player 7 and later, you can cast an expression to an interface type. Unlike Java interfaces, ActionScript interfaces exist at runtime, which allows type casting.
-
Another type of member is a class member. There is only one copy of a class member, which is used for the entire class. The age property would not be a good class member, because each person has a different age. Only properties and methods that are shared by all individuals of the class should be class members. Suppose that you want every class to have a species member that indicates the proper Latin name for the species that the class represents. For every Person object, the species is Homo sapiens.
-
Often there are situations when you need exactly one object of a particular type in a system. For example, in a chess game, there is only one chessboard, and in a country, there is only one capitol city. Even though there is only one object, it is attractive to encapsulate the functionality of this object in a class. However, you might need to manage and access the one instance of that object. Using a global variable is one way to do this, but global variables are often not desirable.
-
The widgetCount variable is declared as static, so it initializes to 0 only once. Each time the Widget class’s constructor function is called, it adds 1 to widgetCount and then shows the number of the current instance that’s being created. 3. Save your file as Widget.as. 4. Create a new FLA document, and save it as createWidget.fla in the same directory as Widget.as. In this file, you’ll create new instances of the Widget class. 5. In createWidget.
-
Implicit getter/setter methods Object-oriented programming practice discourages direct access to properties within a class. Classes typically define getter methods that provide read access and setter methods that provide write access to a given property. For example, imagine a class that contains a property called userName: var userName:String; Instead of allowing instances of the class to directly access this property (obj.
-
return this.userName; } function set user(name:String):Void { this.userName = name; } } A getter method must not take any parameters. A setter method must take exactly one required parameter. A setter method can have the same name as a getter method in the same scope. Getter/ setter methods cannot have the same name as other properties. For example, in the example code above that defines getter and setter methods named user, you could not also have a property named user in the same class.
-
By default, the global classpath contains one absolute path and one relative path. The absolute path is denoted by $(LocalData)/Classes in the Preferences dialog box.
-
In Flash Professional, when you Check Syntax while editing an AS file, the compiler looks only in the global classpath; AS files aren't associated with FLAs in Edit mode and don't have their own classpath. Modifying the classpath You can modify the global classpath using the Preferences dialog box. To modify the documentlevel classpath setting, you use the Publish Settings dialog box for the FLA file.
-
Alternatively, double-click the path in the Classpath list, type the desired path, and click OK. ■ To delete a directory from the classpath, select the path in the Classpath list and click the Remove Selected Path (-) button. Importing classes To reference a class in another script, you must prefix the class name with the class’s package path. The combination of a class’s name and its package path is the class’s fully qualified class name.
-
The following example shows that you can then reference either of the classes directly in the same script: var myRos:Rosencrantz = new Rosencrantz(); var myGuil:Guildenstern = new Guildenstern(); The import statement applies only to the current script (frame or object) in which it’s called. If an imported class is not used in a script, the class is not included in the resulting SWF file’s bytecode, and the class isn’t available to any SWF files that the FLA file containing the import statement might load.
-
If you experience problems in which Flash appears to be compiling older versions of a file you have edited, delete the ASO files and then recompile. If you plan to delete ASO files, delete them when Flash is not performing other operations, such as checking syntax or exporting SWFs. There is a limit to how much code you can place in a single class: The bytecode for a class definition in an exported SWF file cannot be larger than 32,767 bytes.
-
Chapter 10: Creating Custom Classes with ActionScript 2.
-
CHAPTER 11 Working with External Data In Macromedia Flash MX 2004 and Macromedia Flash MX Professional 2004, you can use ActionScript to load data from external sources into a SWF file. You can also send data from a SWF file for processing by an application server (such as Macromedia ColdFusion MX or Macromedia JRun) or another type of server-side script, such as PHP or Perl. Macromedia Flash Player can send and load data over HTTP or HTTPS or load from a local text file.
-
• The functions and MovieClip methods that use the HTTP or HTTPS protocol to send information in URL-encoded format are getURL(), loadVariables(), loadVariablesNum(), loadMovie(), and loadMovieNum(). • The LoadVars methods that use the HTTP or HTTPS protocol to send and load information in URL-encoded format are load(), send(), and sendAndLoad(). • The methods that use HTTP or HTTPS protocol to send and load information as XML are XML.send(), XML.load(), and XML.sendAndLoad().
-
For example, the following ActionScript loads the variables from the file myData.txt into the movie clip loadTarget_mc. An onData() handler assigned to the loadTarget_mc instance uses the variable lastSiteVisited, which is loaded from the file myData.txt. The following trace actions appear only after all the variables, including lastSiteVisited, are loaded: this.createEmptyMovieClip("loadTarget_mc", this.getNextHighestDepth()); this.loadTarget_mc.onData = function() { trace("Data Loaded"); trace(this.
-
For example, if you want to track the high scores for a game, you could store the scores on a server and use loadVariables() to load them into the SWF file each time someone played the game. The function call might look like the following example: loadVariables("http://www.mySite.com/scripts/high_score.cfm", _root.scoreClip, GET); This example loads variables from the ColdFusion script called high_score.cfm into the movie clip instance scoreClip using the GET HTTP method.
-
• The callback interface is through ActionScript methods (onLoad) instead of the obsolete, deprecated onClipEvent (data) approach required for loadVariables. • There are error notifications. • You can add custom HTTP request headers. You must create a LoadVars object to call its methods. This object is a container to hold the loaded data. The following procedure shows how to use ColdFusion and the LoadVars class to send an e-mail from a SWF file.
-
This ActionScript creates a new LoadVars object instance, copies the values from the text fields into the instance, and then sends the data to the server. The CFM file sends the e-mail and returns a variable (true or false) to the SWF file called result, which appears in the debug_txt text field. Note: Remember to change the URL www.yoursite.com to your own domain. 9. Save the document as sendEmail.fla, and then publish it by selecting File > Publish. 10. Upload sendEmail.
-
The following XML class methods send and load XML data to a server by using the HTTP POST method: • The load() method downloads XML from a URL and places it in an ActionScript XML object. • The send()method encodes the XML object into an XML document and sends it to a specified URL using the POST method. If specified, a browser window displays returned data. • The sendAndLoad() method sends an XML object to a URL. Any returned information is placed in an ActionScript XML object.
-
//(optional) Create two text fields for status/debugging //status_txt.text = this.firstChild.attributes.status; //debug_txt.text = this.firstChild; switch (this.firstChild.attributes.status) { case 'OK' : _global.session = this.firstChild.attributes.session; trace(_global.session); gotoAndStop("welcome"); break; case 'FAILURE' : gotoAndStop("loginfailure"); break; default : // this should never happen trace("Unexpected value received for STATUS."); } } else { // trace(“an error occurred.
-
You can test this code by using a user name of JeanSmith and the password VerySecret. The first section of the script generates the following XML when the user clicks the login button: The server receives the XML, generates an XML response and sends it back to the SWF file.
-
Using the XMLSocket class ActionScript provides a built-in XMLSocket class, which lets you open a continuous connection with a server. A socket connection lets the server publish, or push, information to the client as soon as that information is available. Without a continuous connection, the server must wait for an HTTP request. This open connection removes latency issues and is commonly used for realtime applications such as chats.
-
theSocket.send(myXML); } //button sends data sendButton.onRelease = function() { sendData(); }; //traces data returned from socket connection theSocket.onData = function(msg:String):Void { trace(msg); }; For more information, see the “XMLSocket class” entry in Flash ActionScript Language Reference.
-
The following table shows the values you can specify for the command and arguments parameters of fscommand() to control the playback and appearance of a SWF file playing in the stand-alone player, including projectors. Command Arguments Purpose quit None Closes the projector. fullscreen true or false Specifying true sets Flash Player to full-screen mode. Specifying false returns the player to normal menu view.
-
7. In an HTML or text editor, open the HTML file that was generated in step 6 and examine the code. When you published your SWF file using the Flash with FSCommand template on the HTML tab of the Publish Settings dialog box, some additional code was inserted in the HTML file. The SWF file’s NAME and ID attributes are the filename. For example, for the file myMovie.fla, the attributes would be set to myMovie. 8.
-
There are two technologies that enable communication between the browser and Flash Player: LiveConnect (Netscape Navigator 3.0 or later on Windows 95/98/2000/NT/XP or Power Macintosh) and ActiveX (Internet Explorer 3.0 and later on Windows 95/98/2000/NT/XP). Although the techniques for scripting are similar for all browsers and languages, there are additional properties and events available for use with ActiveX controls.
-
For more information, see the following topics: • • • • • • “About allowing data access between cross-domain SWF files” on page 289 “About allowing HTTP to HTTPS protocol access between SWF files” on page 290 “About allowing cross-domain data loading” on page 290 “About custom policy file locations” on page 292 “About XMLSocket policy files” on page 293 “About compatibility with previous Flash Player security models” on page 294.
-
Now the getData function in the loaded SWF file can be called by the macromedia.swf file. Notice that allowDomain permits any SWF file in the allowed domain to script any other SWF file in the domain permitting the access, unless the SWF file being accessed is hosted on a site using a secure protocol (HTTPS). In this case, you must use allowInsecureDomain instead of allowDomain; see the following section. For more information on domain-name matching, see “Flash Player security features” on page 288.
-
For example, a policy file located at https://www.macromedia.com:8080/crossdomain.xml will apply only to data loading calls made to www.macromedia.com over HTTPS at port 8080. An exception to this rule is the use of an XMLSocket object to connect to a socket server in another domain. In that case, an HTTP server running on port 80 in the same domain as the socket server must provide the policy file for the method call.
-
A policy file that contains no tags has the same effect as not having a policy on a server. About custom policy file locations Flash Player 7 (7.0.19.0) supports a new method called System.security.loadPolicyFile. This method lets you specify a custom location on a server where a cross domain policy file can be found, so it does not need to be in the root directory. Flash Player 7 (7.0.14.
-
About XMLSocket policy files For an XMLSocket connection attempt, Flash Player 7 (7.0.14.0) looked for crossdomain.xml on an HTTP server on port 80 in the subdomain to which the connection attempt was being made. Flash Player 7 (7.0.14.0) and all earlier versions restricted XMLSocket connections to ports 1024 and above. However, in Flash Player 7 (7.0.19.0) and later, ActionScript can inform Flash Player of a non-default location for a policy file using System.security.loadPolicyFile.
-
Because the ability to connect to ports lower than 1024 is new in Flash Player 7 (7.0.19.0), a policy file loaded with loadPolicyFile is always required to authorize this, even when a SWF file is connecting to its own subdomain.
-
CHAPTER 12 Working with External Media If you import an image or a sound while you author a document in Macromedia Flash MX 2004 or Macromedia Flash MX Professional 2004, the image and sound are packaged and stored in the SWF file when you publish it. In addition to importing media while authoring, you can load external media, including other SWF files, at runtime. There are several reasons you might want to keep media outside a Flash document.
-
To play back an external MPEG Layer 3 (MP3) file, use the loadSound() method of the Sound class. This method lets you specify whether the MP3 file should progressively download or finish downloading completely before it starts to play. You can also read the ID3 information embedded in MP3 files, if they’re available. For more information, see “Reading ID3 tags in MP3 files” on page 298. Flash Video (FLV) is the native video format used by Flash Player.
-
The following code loads the JPEG image flowers.jpg into the movie clip instance image_clip: image_clip.loadMovie("flowers.jpg"); For more information about these methods, see loadMovie(), loadMovieNum(), and MovieClip.loadMovie() in Flash ActionScript Language Reference. For more information about loading external SWF and JPEG files, see the next section. About loaded SWF files and the root Timeline The ActionScript property _root specifies or returns a reference to the root Timeline of a SWF file.
-
In most cases, set the isStreaming parameter to true, especially if you’re loading large sound files that should start playing as soon as possible—for example, when creating an MP3 “jukebox” application. However, if you’re downloading shorter sound clips and need to play them at a specified time (for example, when a user clicks a button), set isStreaming to false. To determine when a sound has completely downloaded, use the Sound.onLoad event handler.
-
The onID3 event handler is called each time new ID3 data is available. This means that if an MP3 file contains ID3 2.0 tags and ID3 1.0 tags, the onID3 handler will be called twice because the tags are located in different parts of the file. For a list of supported ID3 tags, see Sound.id3 in Flash ActionScript Language Reference.
-
To play back an external FLV file in a Flash document: 1. With the document open in the Flash authoring tool, in the Library panel (Window > Library) select New Video from the Library options menu to create a video object. 2. Drag a video object from the Library panel onto the Stage; this creates a video object instance. 3. With the video object selected on the Stage, in the Property inspector (Window > Properties) enter my_video in the Instance Name text box. 4.
-
Preloading SWF and JPEG files To preload SWF and JPEG files into movie clip instances, you can use the “MovieClipLoader class”. This class provides an event listener mechanism to give notification about the status of file downloads into movie clips.
-
To display download progress using the ProgressBar component: 1. In a new Flash document, create a movie clip on the Stage and give it an instance name target_mc. 2. Open the Components panel (Window > Development Panels > Components). 3. Drag a ProgressBar component from the Components panel to the Stage. 4. In the Property inspector, give the ProgressBar component the name pBar and, on the Parameters tab, select Manual from the Mode pop-up menu. 5.
-
trace("%" + percentLoaded + " loaded."); }; // When the file has finished loading, clear the interval polling. songTrack.onLoad = function () { clearInterval(poll); }; // Load streaming MP3 file and start calling checkProgress() songTrack.loadSound("http://yourserver.com/songs/beethoven.mp3", true); var poll = setInterval(checkProgress, 1000, songTrack); You can use this same kind of polling technique to preload external FLV files.
-
Chapter 12: Working with External Media
-
APPENDIX A Error Messages Macromedia Flash MX 2004 and Macromedia Flash MX Professional 2004 provide enhanced compile-time error reporting when you publish to ActionScript 2.0 (the default). The following table contains a list of error messages that the Flash compiler can generate: Error number Message text 1093 A class name was expected. 1094 A base class name is expected after the ‘extends’ keyword. 1095 A member attribute was used incorrectly.
-
Error number Message text 306 1114 There is no interface defined with this name. 1115 A class may not extend an interface. 1116 An interface may not extend a class. 1117 An interface name is expected after the ‘implements’ keyword. 1118 A class may not implement a class, only interfaces. 1119 The class must implement method ‘methodName’ from interface ‘interfaceName’. 1120 The implementation of an interface method must be a method, not a property.
-
Error number Message text 1144 Instance variables cannot be accessed in static functions. 1145 Class and interface definitions cannot be nested. 1146 The property being referenced does not have the static attribute. 1147 This call to super does not match the superconstructor. 1148 Only the public attribute is allowed for interface methods. 1149 The import keyword cannot be used as a directive. 1150 You must export your movie as Flash 7 to use this action.
-
Error number Message text 308 1174 The class or interface name you have entered contains a syntax error. 1175 ‘variable’ is not accessible from this scope. 1176 Multiple occurrences of the ‘get/set/private/public/static’ attribute were found. 1177 A class attribute was used incorrectly. 1178 Instance variables and functions may not be used to initialize static variables. 1179 Runtime circularities were discovered between the following classes: .
-
Error number Message text 1198 The member function ‘’ has a different case from the name of the class being defined, ‘’, and will not be treated as the class constructor at runtime. 1199 The only type allowed for a for-in loop iterator is String. 1200 A setter function may not return a value. 1201 The only attributes allowed for constructor functions are public and private.
-
Appendix A: Error Messages
-
APPENDIX B Deprecated Flash 4 operators The following table lists Flash 4-only operators, which are deprecated in ActionScript 2.0. Do not use these operators unless you are publishing to Flash Player 4 and earlier.
-
Appendix B: Deprecated Flash 4 operators
-
APPENDIX C Keyboard Keys and Key Code Values The following tables list all the keys on a standard keyboard and the corresponding ASCII key code values that are used to identify the keys in ActionScript: • • • • “Letters A to Z and standard numbers 0 to 9” “Keys on the numeric keypad” on page 314 “Function keys” on page 315 “Other keys” on page 316 Letters A to Z and standard numbers 0 to 9 The following table lists the keys on a standard keyboard for the letters A to Z and the numbers 0 to 9, with the c
-
Letter or number key Key code N 78 O 79 P 80 Q 81 R 82 S 83 T 84 U 85 V 86 W 87 X 88 Y 89 Z 90 0 48 1 49 2 50 3 51 4 52 5 53 6 54 7 55 8 56 9 57 Keys on the numeric keypad The following table lists the keys on a numeric keypad, with the corresponding ASCII key code values that are used to identify the keys in ActionScript: 314 Numeric keypad key Key code Numbpad 0 96 Numbpad 1 97 Numbpad 2 98 Numbpad 3 99 Numbpad 4 100 Appendix C: Keyboard Keys a
-
Numeric keypad key Key code Numbpad 5 101 Numbpad 6 102 Numbpad 7 103 Numbpad 8 104 Numbpad 9 105 Multiply 106 Add 107 Enter 13 Subtract 109 Decimal 110 Divide 111 Function keys The following table lists the function keys on a standard keyboard, with the corresponding ASCII key code values that are used to identify the keys in ActionScript: Function key Key code F1 112 F2 113 F3 114 F4 115 F5 116 F6 117 F7 118 F8 119 F9 120 F10 This key is reserved by the system
-
Other keys The following table lists keys on a standard keyboard other than letters, numbers, numeric keypad keys, or function keys, with the corresponding ASCII key code values that are used to identify the keys in ActionScript: 316 Key Key code Backspace 8 Tab 9 Clear 12 Enter 13 Shift 16 Control 17 Alt 18 Caps Lock 20 Esc 27 Spacebar 32 Page Up 33 Page Down 34 End 35 Home 36 Left Arrow 37 Up Arrow 38 Right Arrow 39 Down Arrow 40 Insert 45 Delete 46 Help 47 Nu
-
Key Key code ]} 221 "' 222 Other keys 317
-
Appendix C: Keyboard Keys and Key Code Values
-
APPENDIX D Writing Scripts for Earlier Versions of Flash Player ActionScript has changed considerably with the release of Macromedia Flash MX 2004 and Macromedia Flash MX Professional 2004. When you create content for Macromedia Flash Player 7, you can use the full power of ActionScript. You can still use Flash MX 2004 to create content for earlier versions of Flash Player, but you can’t use every ActionScript element.
-
Using Flash MX 2004 to create content for Flash Player 4 To use Flash MX 2004 to create content for Flash Player 4, specify Flash Player 4 on the Flash tab of the Publish Settings dialog box (File > Publish Settings). Flash Player 4 ActionScript has only one basic primitive data type, which is used for numeric and string manipulation. When you write an application for Flash Player 4, you must use the deprecated string operators located in the Deprecated > Operators category in the Actions toolbox.
-
In Flash 4 ActionScript, these operators were always numeric operators. In Flash 5 and later, they behave differently, depending on the data types of the operands. To prevent any semantic differences in imported files, the Number() function is inserted around all operands to these operators. (Constant numbers are already obvious numbers, so they are not enclosed in Number()).
-
Appendix D: Writing Scripts for Earlier Versions of Flash Player
-
APPENDIX E Object-Oriented Programming with ActionScript 1 The information in this appendix comes from the Macromedia Flash MX documentation and provides information on using the ActionScript 1 object model to write scripts. It is included here for the following reasons: • If you want to write object-oriented scripts that support Flash Player 5, you must use ActionScript 1. • If you already use ActionScript 1 to write object-oriented scripts and aren’t ready to switch to ActionScript 2.
-
Objects in ActionScript can be pure containers for data, or they can be graphically represented on the Stage as movie clips, buttons, or text fields. All movie clips are instances of the built-in MovieClip class, and all buttons are instances of the built-in Button class. Each movie clip instance contains all the properties (for example, _height, _rotation, _totalframes) and all the methods (for example, gotoAndPlay(), loadMovie(), startDrag()) of the MovieClip class.
-
Creating a custom object in ActionScript 1 To create a custom object, you define a constructor function. A constructor function is always given the same name as the type of object it creates. You can use the keyword this inside the body of the constructor function to refer to the object that the constructor creates; when you call a constructor function, Flash passes this to the function as a hidden parameter.
-
To assign a method to a custom object: 1. Define the constructor function Circle(): function Circle(radius) { this.radius = radius; } 2. Define the getArea() method of the Circle object. The getArea() method calculates the area of the circle. In the following example, you can use a function literal to define the getArea() method and assign the getArea property to the circle’s prototype object: Circle.prototype.getArea = function () { return Math.PI * this.radius * this.radius; }; 3.
-
This new class is assigned to all instances of the movie clip that are added to the application by the Timeline or that are added to the application with the attachMovie() or duplicateMovieClip() method. If you want these movie clips to have access to the methods and properties of the built-in MovieClip object, you need to make the new class inherit from the MovieClip class. 3. Enter code, such as the following example: // inherit from MovieClip class myClipClass.
-
myClipClass.prototype.myfunction = function(){ trace("myfunction called"); } Object.registerClass("myclipID",myClipClass); this.attachMovie("myclipID","clipName",3); Creating inheritance in ActionScript 1 Inheritance is a means of organizing, extending, and reusing functionality. Subclasses inherit properties and methods from superclasses and add their own specialized properties and methods.
-
Instead of adding roll() to the MountainBike class and the Tricycle class, you can create the MountainBike class with Bike as its superclass, as shown in the following example: MountainBike.prototype = new Bike(); Now you can call the roll() method of MountainBike, as shown in the following example: var myKona = new MountainBike(20, "teal"); trace(myKona.roll()); //traces 20 Movie clips do not inherit from each other. To create inheritance with movie clips, you can use Object.
-
Using Function object properties in ActionScript 1 You can specify the object to which a function is applied and the parameter values that are passed to the function, using the call() and apply() methods of the Function object. Every function in ActionScript is represented by a Function object, so all functions support call() and apply().
-
For more information, see Function.apply() in Flash ActionScript Language Reference. To specify the object to which a function is applied using Function.apply(): • Use the following syntax: myFunction.apply(thisObject, argumentsObject) The method takes the following parameters: ■ ■ The parameter thisObject specifies the object to which myFunction is applied. The parameter argumentsObject defines an array whose elements are passed to myFunction as parameters.
-
Appendix E: Object-Oriented Programming with ActionScript 1
-
INDEX A accessing object properties 56 actions coding standards 83 repeating 59 Actions panel 140 Actions toolbox 141 yellow items in 144 ActionScript comparing versions 84 editor 141, 144 Flash Player 85 interfaces 263 strict data typing not supported in ActionScript 1 42 writing 85 ActionScript 2.0 assigning ActionScript 2.
-
C calling methods 37 capturing keypresses 184 cascading style sheets and TextField.StyleSheet class 228 applying style classes 231 applying to text fields 230 assigning styles to built-in HTML tags 231 combining styles 231 defining styles in ActionScript 229 example of using with HTML tags 232 example of using with XML tags 235 formatting text 226 loading 228 properties supported 227 using to define new tags 234 casting data types 42 character sequences.
-
reserved words 75 variable names 70 coding standards 82 organizing scripts 82 collisions, detecting 192 between movie clip and Stage point 193 between movie clips 193 colors in Actions toolbox 144 values, setting 187 combining operations 55 comments 31 in classes 102 in code 77 communicating with the Flash Player 285 comparison operators 52 compile time, defined 9 completion, code 78 component-based architecture, defined 205 components, coding conventions 74 compound statements 91 concatenating strings 35 c
-
dot operators 56 dot syntax 29 dragging movie clips 210 drawing lines and fills 194 shapes 216 duplicating, movie clips 212 dynamic classes 259 E ECMA-262 compliance 14 specification 24 encapsulation 249 encoding text 152 equality operators 54 different from assignment operators 54 strict 55 errors list of error messages 305 name conflict 46 escape sequences 35 Escape shortcut keys 149 event handler methods 167 in ActionScript 2.
-
best practices 98 built-in 60 calling 63 coding conventions 72 constructor 324 conversion 35 custom 61 defining 61 for controlling movie clips 206 local variables in 62 passing parameters to 62 returning values 62 sample 27 G garbage collection 89 getAscii() method 184 getter/setter methods of classes 267 getting information from remote files 275 getting mouse pointer position 183 getURL() method 181 global classpaths 268 global variables 46 and strict data typing 41 grouping statements 30, 31, 32 H handler
-
K key codes, ASCII function keys 315 getting 184 letter and number keys 313 numeric keypad 314 other keys 316 keyboard ASCII key code values 313 shortcuts for pinned scripts 143 keyboard controls and Test Movie 153 to activate movie clips 186 keypresses, capturing 184 keywords 26 listed 32 L languages, using multiple in scripts 152 levels 58 loading 207 line numbers in code, displaying 152 linkage coding conventions 74 identifier 212, 218 Linkage Properties dialog box 212, 218 linking, movie clips 212 List
-
loading SWF files and JPEG files into 296 looping through children 60 managing depth 215 methods 206 methods and functions compared 205 methods, using to draw shapes 216 nested, defined 205 parent, defined 205 properties 209 properties, initializing at runtime 219 removing 212 sharing 212 starting and stopping 180 using as masks 217 See also SWF files moviename_DoFSCommand function 286 MP3 files and ID3 tags 298 loading into movie clips 297 preloading 302 multidimensional arrays 57 multiple inheritance, not
-
P packages 260 coding conventions 73 naming 260 parameters defined 27 in parentheses 31 passing to functions 62 parent movie clips, defined 205 parentheses 31 checking for matching pairs 151 passing values by content 47 by reference 48 passwords and remote debugging 155 pausing (stepping through) code 160 pinning scripts in place 143 Player, ActionScript 85 playing movie clips 180 pointer. See cursors policy files 290 must be named crossdomain.
-
scrolling text 244 security 288–294 and policy files 290 and porting scripts to Flash Player 7 15, 18, 19 data access across domains 289, 290 loadPolicyFile 292, 293 semicolon 31 sending information in XML format 276 to remote files 275 URL-encoded format 276 via TCP/IP 276 server-side scripts languages 275 XML format 281 servers, opening continuous connection 284 setRGB method 187 slash syntax 30 not supported in ActionScript 2.
-
Test Movie and keyboard controls 153 and Unicode 153 testing.
-
writing syntax and statements 89 compound 91 conditional 90 do-while 92 for statement 92 listener 94 return 93 switch 93 try-catch and try-catch-finally 93 X XML 280 DOM 280 example of using with styles 235 hierarchy 280 in server-side scripts 281 sample variable conversion 280 sending information via TCP/IP socket 276 sending information with XML methods 276 XML class, methods of 280 XMLSocket object checking for data 277 loadPolicyFile 293 methods of 284 using 284 Index 343
-
Index