MACROMEDIA FLASH MX 2004-USING ACTIONSCRIPT IN FLASH Use Manual
MACROMEDIA FLASH MX 2004-USING ACTIONSCRIPT IN FLASH Use Manual

MACROMEDIA FLASH MX 2004-USING ACTIONSCRIPT IN FLASH Use Manual

Using actionscript in flash
Hide thumbs Also See for FLASH MX 2004-USING ACTIONSCRIPT IN FLASH:
Table of Contents

Advertisement

Quick Links

Using ActionScript in Flash

Advertisement

Table of Contents
loading
Need help?

Need help?

Do you have a question about the FLASH MX 2004-USING ACTIONSCRIPT IN FLASH and is the answer not in the manual?

Questions and answers

Summary of Contents for MACROMEDIA FLASH MX 2004-USING ACTIONSCRIPT IN FLASH

  • Page 1 Using ActionScript in Flash...
  • Page 2 Open Sesame!, Roundtrip, Roundtrip HTML, Shockwave, Sitespring, SoundEdit, Titlemaker, UltraDev, Web Design 101, what the web can be, and Xtra are either registered trademarks or trademarks of Macromedia, Inc. and may be registered in the United States or in other jurisdictions including internationally. Other product names, logos, designs, titles, words, or phrases mentioned within this publication may be trademarks, service marks, or trade names of Macromedia, Inc.
  • Page 3: Table Of Contents

    CONTENTS INTRODUCTION: Getting Started with ActionScript ..... . . 7 Intended audience ..........7 System requirements .
  • Page 4 Behaviors conventions ..........105 Screens conventions.
  • Page 5 Adding parameters to dynamically created movie clips ....213 Managing movie clip depths ........215 Drawing shapes with ActionScript.
  • Page 6 APPENDIX A: Error Messages ........305 APPENDIX B: Deprecated Flash 4 operators .
  • Page 7: Introduction: Getting Started With Actionscript

    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.
  • Page 8 • 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.
  • Page 9: Typographical Conventions

    These applications were designed to introduce new Flash developers to the capabilities of Flash applications as well as show advanced developers how Flash features work in context. On Windows, you can find the applications in \Program Files\Macromedia\Flash MX 2004\ Examples. On the Macintosh, you can find the applications in HD/Applications/Macromedia Flash MX 2004/Examples.
  • Page 10 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.
  • Page 11: Chapter 1: What's New In Flash Mx 2004 Actionscript

    13). Updating Flash XML files It is important that you always have the latest Flash XML files installed. Macromedia sometimes introduces features in dot releases (minor releases) of Flash Player. When such a release is available, you should update your version of Flash to get the latest XML files. Otherwise, the Flash MX 2004 compiler might generate errors if you use new properties or methods that were unavailable in the version of Flash Player that came with your Flash installation.
  • Page 12: New And Changed Language Elements

    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. •...
  • Page 13: New Security Model And Legacy Swf Files

    • property lets you remove extra white space from HTML text TextField.condenseWhite fields that are rendered in a browser. • property lets you specify whether a text field’s contents TextField.mouseWheelEnabled should scroll when the mouse pointer is positioned over a text field and the user rolls the mouse wheel.
  • Page 14: Ecma-262 Compliance

    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.
  • Page 15: Domain-Name Rules For Settings And Local Data

    SWF file published for Flash Player 7 SWF file published for earlier versions of Flash Player When is converted to a string, the result is When is converted to a string, the undefined undefined result is an empty string (""). undefined firstname = "Joan ";...
  • Page 16 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 handler LocalConnection.allowDomain method to specify permitted cross-domain access (for System.security.allowDomain() 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.someSite.com).
  • Page 17 System.security.allowDomain domain-name matching, as shown in the code examples earlier in this section. (LocalConnection objects aren’t supported in Flash Player 5 or earlier.) For more information, see the tech note at www.macromedia.com/support/flash/ts/documents/ security_sandbox.htm. Porting existing scripts to Flash Player 7...
  • Page 18: Http To Https Protocol Access Between Swf Files

    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.
  • Page 19: Server-Side Policy Files For Permitting Access To Data

    XML.load() XML.sendAndLoad() LoadVars.load() LoadVars.sendAndLoad() loadVariables() loadVariablesNum(), , and Macromedia Flash Remoting MovieClip.loadVariables() XMLSocket.connect() ). Also, a SWF file can import runtime shared NetServices.createGatewayConnection libraries (RSLs), or assets defined in another SWF file, at runtime. By default, the data or RSL must reside in the same domain as the SWF file that is loading that external data or media.
  • Page 20: Actionscript Editor Changes

    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.
  • Page 21: Debugging Changes

    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.
  • Page 22 • interface • dynamic • static • public • private • • • 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;...
  • Page 23: Chapter 2: Actionscript Basics

    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.
  • Page 24: Differences Between Actionscript And Javascript

    ECMA-262 specification. • ActionScript does not support regular expressions using the RegExp object. However, Macromedia Central does support the RegExp object. Terminology As with all scripting languages, ActionScript uses its own terminology. The following list provides...
  • Page 25 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 {...
  • Page 26 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();...
  • Page 27 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.
  • Page 28: Syntax

    Syntax As with all scripting languages, ActionScript has syntax rules that you must follow to create scripts that can compile and run correctly. This section describes the elements that comprise ActionScript syntax: • “Case sensitivity” on page 28 • “Dot syntax” on page 29 •...
  • Page 29 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 to load a Flash Player 6 SWF into a Flash Player 7 SWF, the loadMovie() version 6 SWF remains case-insensitive, while the version 7 SWF is treated as case-sensitive.
  • Page 30 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.
  • Page 31 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.
  • Page 32 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();...
  • Page 33 extends finally function ifFrameLoaded implements import instanceof interface intrinsic onClipEvent private public return static switch tellTarget this throw typeof void while with All class names, component class names, and interface names are reserved words: Accessibility Accordion Alert Array Binding Boolean Button Camera CellRenderer...
  • Page 34: About Data Types

    WebServiceConnector Window XMLConnector XUpdateResolver Constants A constant is a property whose value never changes. ActionScript contains predefined constants. For example, the constants , and are properties of the Key object BACKSPACE ENTER SPACE 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?";...
  • Page 35 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.
  • Page 36 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 (...
  • Page 37 submit_button.addEventListener("click", btnListener); For more information, see “Using built-in functions” on page 60 “Logical operators” on page 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.
  • Page 38 + product); The second example returns the width of a movie clip called on the Stage. The targeted my_mc instance must be a movie clip, and the returned value must be a numeric value. function getMCWidth(target_mc:MovieClip):Number { return target_mc._width;...
  • Page 39: Assigning Data Types To Elements

    Null data type The null data type has only one value, . This value means no value—that is, a lack of data. null You can assign the value in a variety of situations to indicate that a property or variable does null not yet have a value assigned to it.
  • Page 40 • 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.
  • Page 41 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.
  • Page 42 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.
  • Page 43 In this situation, you asserted to the compiler that is a Dog object, and, therefore, the compiler assumes that ; is a legal statement. However, the compiler doesn’t know temp.bark() that the cast will fail (that is, that you tried to cast a Cat object to an Animal type), so no compile- time error occurs.
  • Page 44: About Variables

    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.
  • Page 45 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 , the new object is undefined: new String() // This code works as expected...
  • Page 46 Make sure to declare a Timeline variable before trying to access it in a script. For example, if you put the code in Frame 20, a script attached to any frame before Frame 20 cannot var x = 10; access that variable. Local variables To declare local variables, use the statement inside the body of a function.
  • Page 47 //works var myWebSite = "http://www.macromedia.com"; getURL(myWebSite); // browser displays www.macromedia.com You can change the value of a variable in a script as many times as you want. The type of data that a variable contains affects how and when the variable’s value changes.
  • Page 48 In the following example, the variable contains a primitive value, 3, so that value is inValue passed to the function and the returned value is 9: sqr() function sqr(x:Number):Number { var x:Number = x * x; return x; var inValue:Number = 3; var out:Number = sqr(inValue);...
  • Page 49: Using Operators To Manipulate Values In Expressions

    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.
  • Page 50 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;...
  • Page 51 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 <= >...
  • Page 52 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 ). These operators are most commonly used in loops and in conditional statements. In the false following example, if the variable , a certain function is called;...
  • Page 53 Operator Operation performed <= Less than or equal to: Returns if the left operand is mathematically smaller than true or the same as the right operand. Returns if the left operand alphabetically precedes or is the same as the right true operand.
  • Page 54 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, will be greater than 50, consider putting the condition first;...
  • Page 55 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 . The strict inequality ( ) operator false returns the opposite of the strict equality operator.
  • Page 56 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...
  • Page 57: Specifying An Object's Path

    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 function to dynamically set and retrieve instance names and variables, as eval() shown in the following example: eval("mc"...
  • Page 58: Using Condition Statements

    To dynamically create a movie clip: • Use the , or MovieClip.attachMovie() MovieClip.createEmptyMovieClip() method. The following example uses the MovieClip.duplicateMovieClip() method to dynamically create the movie clip and place it on attachMovie() purpleDot2_mc top of the movie clip when the user rolls over the clip, which is on greenBox_mc greenBox_mc...
  • Page 59 gotoAndPlay("startProgram"); If you want to check for one of several conditions, you can use the statement rather than switch multiple statements. else if Repeating actions ActionScript can repeat an action a specified number of times or while a specific condition exists. Use the , and actions to create loops.
  • Page 60: Using Built-In Functions

    To loop through the children of a movie clip or an object: • Use the statement. for..in Children include other movie clips, functions, objects, and variables. The following example uses statement to print its results in the Output panel: trace var myObject:Object = { name:'Joe', age:25, city:'San Francisco' };...
  • Page 61: Creating Functions

    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.”...
  • Page 62: Passing Parameters To A Function

    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 finalScore function fillOutScorecard(initials:String, finalScore:Number):Void { scorecard.display = initials;...
  • Page 63: Calling A User-Defined Function

    For example, the following function returns the square of the parameter 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;...
  • Page 64 Chapter 2: ActionScript Basics...
  • Page 65: Chapter 3: Using Best Practices

    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.
  • Page 66: Working With Fla Files

    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.
  • Page 67 • 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.
  • Page 68 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)”...
  • Page 69: General Coding Conventions

    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.
  • Page 70 Limit your use of abbreviations, but use them consistently. An abbreviation must clearly stand for only one thing. For example, the abbreviation 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.
  • Page 71 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.
  • Page 72 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"; //constant var MAX_WIDTH:Number = 10; //constant Write static constants in uppercase, and separate words with an underscore. Do not directly code...
  • Page 73 Put the prefix for a package name in all lowercase letters. Begin package names with to maintain consistency when naming classes. The next parts of the package com.macromedia name vary, depending on the particular naming scheme. For example, a convention might use one of the following package names: mx.containers.ScrollPane...
  • Page 74 If you develop custom components, use a naming convention to prevent naming collisions with Macromedia components. The names of your components must be different from those of the default set that is included with Flash. Adopting your own consistent naming convention prevents naming conflicts.
  • Page 75 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.
  • Page 76 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...
  • Page 77 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.
  • Page 78 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.
  • Page 79 To strict data type your variables, you must define the variable using the 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.
  • Page 80 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.
  • Page 81 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. Object Suffix Accordion _acc Alert _alert Button _button CheckBox ComboBox DataGrid DateChooser...
  • Page 82: Actionscript Coding Standards

    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”...
  • Page 83 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.
  • Page 84 Attaching ActionScript to a button called looks like the following ActionScript, myButton_btn 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”...
  • Page 85 SWF file from the server. For example, if you use a Macromedia ColdFusion web service, property names from a structure or object might be all uppercase, such as .
  • Page 86 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 •...
  • Page 87 Using trace statements statements in your documents to help you debug your code while authoring the FLA trace file. For example, by using a statement and loop, you can see the values of variables in trace 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"];...
  • Page 88 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 statement. When you do not specify a variable’s scope, you do not always know where you with are setting properties, so your code can be confusing.
  • Page 89 Delete variables or make variables when you no longer need them. Setting variables to null 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.
  • Page 90 Writing conditional statements Place conditions put on separate lines in , and statements. Your else-if if-else statements should use braces ( ). You should format braces like the following examples. The , and statements have the following formats: if-else else-if //if statement if (condition) { //statements;...
  • Page 91 The shortened statement syntax is known as the conditional operator ( ). It lets you convert simple statements into a single line of code. In this case, the shortened syntax reduces if-else readability, and so it is not preferable. Do not use this syntax for complex code, because it is more difficult to spot errors.
  • Page 92 Using the for statement Write the statement using the following format: for (init; condition; update) { // statements; The following structure demonstrates the 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 statement.
  • Page 93 Using return statements Do not use parentheses [()]with any statements that have values. The only time you return should use parentheses with statements is when it makes the value more obvious, which is return shown in the third line of the following ActionScript: return;...
  • Page 94 9x120_box_flashpro.jpg"); The following example shows another recommended way of using a listener. In this example, you define a function that is called when the user presses a Button component instance on the Stage: var submit_button:mx.controls.Button;...
  • Page 95 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. The following example includes a space after a keyword that is followed by parentheses [()]: do { //something } while (condition);...
  • Page 96 • “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 ; these are discussed later _root in this section. Avoid using in ActionScript because it can cause SWF files that load into _root other SWF files to not work correctly.
  • Page 97 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.m_username = username;...
  • Page 98 // 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 handler, the onLoad keyword actually refers to the instance and not the class, which you this prod_xml...
  • Page 99: Using Classes And Actionscript 2.0

    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;...
  • Page 100: Creating And Organizing Classes

    For example, if you are following the recommended naming guidelines, you might use the following statement: import com.macromedia.Utils; The next line of a class is a package statement, class declaration, or interface declaration, as the following example shows: class com.macromedia.users.UserClass{...}...
  • Page 101 //statements; This code declares the same variable inside an inner block, which is a practice you should avoid. The following example shows the organization of a simple class: class com.macromedia.users.UserClass { private var m_username:String; private var m_password:String; public function UserClass(username:String, password:String) { this.m_username = username;...
  • Page 102: Programming Classes

    For example, you might create documentation for your class that is similar to the following comment: User class version 1.2 3/21/2004 copyright Macromedia, Inc. Chapter 3: Using Best Practices...
  • Page 103: Wrapping Lines Of Code

    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.
  • Page 104: Using Design Patterns

    For more information on the Singleton design pattern, see www.macromedia.com/devnet/mx/coldfusion/articles/design_patterns.html. 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 capital city.
  • Page 105: Behaviors Conventions

    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.
  • Page 106 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.
  • Page 107: Screens Conventions

    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”...
  • Page 108 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.
  • Page 109 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.
  • Page 110: Video Conventions

    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.
  • Page 111 For more information on the Flash Player specifications, see http://download.macromedia.com/pub/flash/flash_file_format_specification.pdf. To export video as an FLV file: Select the video symbol in the library, right-click (Windows) or Control-click (Macintosh), and select Properties from the context menu.
  • Page 112 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.
  • Page 113 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”...
  • Page 114: Performance And Flash Player

    Note: The best bitmap format to import into Flash is PNG, which is the native file format of Macromedia Fireworks. PNG files have RGB and alpha information for each pixel. If you import a Fireworks PNG file into Flash, you retain some ability to edit the graphic objects in the FLA file.
  • Page 115 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.
  • Page 116 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.
  • Page 117 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.
  • Page 118 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.
  • Page 119 Using in your code forces the SWF file to use the system’s code page System.useCodepage 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.
  • Page 120 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: •...
  • Page 121: Guidelines For Flash Applications

    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.
  • Page 122 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.
  • Page 123 If that MIME type is missing, the result is usually unusable when it reaches Flash. There are other formats for sending data, ranging from XML, Macromedia Flash Remoting, web services, server-side ActionScript (SSAS), or you can even send data using the MovieClip class’s method.
  • Page 124 Scene 1. For more information about using complex data with your web service, see www.macromedia.com/support/flash/ts/documents/webserviceflaws.htm. Adding data validation and loading Try to validate any information you retrieve before you send that data to a server. This reduces strain on the remote server, because it does not handle as many requests when users do not fill in required fields.
  • Page 125 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.
  • Page 126 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.
  • Page 127: Projects And Version Control Guidelines

    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.
  • Page 128 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.
  • Page 129: Guidelines For Accessibility In Flash

    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.
  • Page 130: Creating Accessible Sites

    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.
  • Page 131: Using Screen Readers

    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.
  • Page 132: Controlling Descriptions And Repetition

    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.
  • Page 133: Ordering, Tabbing, And The Keyboard

    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.
  • Page 134: Handling Audio And Animation

    Flash, see “Accessibility for hearing-impaired users” in Using Flash. For information on using Hi-Caption SE and the Hi-Caption Viewer component, see www.macromedia.com/software/flash/extensions. This third-party extension lets you create captions that you save in an XML file and load into the SWF file at runtime, among other advanced controls.
  • Page 135: Testing Frequently And Making Changes

    Play to Pause), is that change announced by the screen reader? There is no official tool available for validating SWF files, unlike HTML validation. However, some third-party tools exist to help you validate the file. For more information on these extensions, see www.macromedia.com/software/flash/extensions. Guidelines for accessibility in Flash...
  • Page 136: Advertising With Flash

    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.
  • Page 137 Use the command to pass data between an advertisement and a server, and do not use the command. For more information on GET and POST, see in Flash ActionScript POST getURL() Language Reference. Note: Remember to provide control to the user. If you add sound to an advertisement, also add a mute button.
  • Page 138 <PARAM NAME=movie VALUE="your_ad.swf?clickTAG =http://adnetwork.com/tracking?http://www.destinationURL.com"> 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. To learn more about and download the Flash Ad Kit, which helps you deliver integrated and sophisticated advertisements, see www.macromedia.com/devnet/rich_media_ads/articles/flash_ad_kit.html.
  • Page 139: Chapter 4: Writing And Debugging Scripts

    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...
  • Page 140: Controlling When Actionscript Runs

    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.
  • Page 141 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. •...
  • Page 142 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.
  • Page 143 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.
  • Page 144: Using The Actionscript Editor

    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+.
  • Page 145: Writing Code That Triggers Code Hints

    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.
  • Page 146 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.
  • Page 147: Using Code Hints

    Array methods and properties; and so on. // Object theObject; // Array theArray; // MovieClip mc; However, Macromedia recommends that, instead of this technique, you use strict data typing (see “Strictly typing objects to trigger code hints” on page 145) or suffixes (see “Using suffixes to trigger code hints”...
  • Page 148 To work with tooltip-style code hints: Display the code hint by typing an opening parens [ ] after an element that requires parentheses (such as a method name, a command such as , and so on). do while The code hint appears. Note: If a code hint doesn’t appear, make sure you haven’t disabled code hints on the ActionScript tab.
  • Page 149: Using Escape Shortcut Keys

    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”...
  • Page 150: Checking Syntax And Punctuation

    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.
  • Page 151: Formatting Code

    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”...
  • Page 152: Unicode Support For Actionscript

    Command+Shift+W (Macintosh) to enable or disable line numbers. Unicode support for ActionScript Macromedia Flash MX 2004 and Macromedia Flash MX Professional 2004 support Unicode text encoding for ActionScript. This means that you can include text in different languages in an ActionScript file.
  • Page 153: Debugging Your Scripts

    To select text encoding options for importing or exporting ActionScript files: In the Preferences dialog box (Edit > Preferences), click the ActionScript tab. 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.
  • Page 154 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.
  • Page 155 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.
  • Page 156 To activate the Debugger from a remote location: Open the Flash authoring application. 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.
  • Page 157 , or "Hello" 3523 "http:// , and you cannot use . The value can be a www.macromedia.com" x + 2 eval("name:" +i) string (any value surrounded by quotation marks [""]), a number, or a Boolean value ( true false Note: To write the value of an expression to the Output panel in test mode, use the statement.
  • Page 158 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.
  • Page 159 To display a movie clip’s properties in the Debugger: Select a movie clip from the display list. 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 , but you "clearwater"...
  • Page 160 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.
  • Page 161 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 wherever it is defined in the myFunction() 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.
  • Page 162: Using The Output Panel

    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.
  • Page 163 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.
  • Page 164 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.
  • Page 165: Updating Flash Player For Testing

    = 0; trace("onClipEvent enterFrame "+i++); Updating Flash Player for testing You can download the latest version of Flash Player from the Macromedia Support Center at www.macromedia.com/support/flash and use it to test your SWF files with the most recent version of Flash Player.
  • Page 166 Chapter 4: Writing and Debugging Scripts...
  • Page 167: Chapter 5: Handling Events

    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.
  • Page 168 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.
  • Page 169: Using Event Listeners

    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.text = "I just lost keyboard focus";...
  • Page 170 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 , can be problematic when various pieces of code are XML.onLoad listening to the same event;...
  • Page 171: Using Button And Movie Clip Event Handlers

    To create a simple focus manager with event listeners: Using the Text tool, create a text field on the Stage. 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. Create another input text field below the first one.
  • Page 172 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 only to movie clip instances that have been placed on onClipEvent() on() the Stage during authoring.
  • Page 173: Broadcasting Events From Component Instances

    Using on() and onClipEvent() with event handler methods You can, in some cases, use different techniques to handle events without conflict. Using on() doesn’t conflict with using event handler methods that you define. onClipEvent() 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 method, for...
  • Page 174: Event Handler Scope

    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() handlers. If you’re defining an event handler in a new ActionScript 2.0 class, onClipEvent() the scope also depends on how you define the event handler.
  • Page 175 When attached to a button object, the function applies to the Timeline that contains the play() button—that is, the button’s parent Timeline. But when the handler is attached to a on(press) movie clip object, the function call applies to the movie clip that bears the handler. If you play() attach the following code to a movie clip, it plays the parent Timeline: // Attached to movie clip...
  • Page 176: Scope Of The This Keyword

    This code cannot work correctly because there is a problem involving scope with the event handlers, and what refers to is confused between the event handler and the class. this onLoad The behavior that you might expect in this example is that the method will onLoadVarsDone() be invoked in the scope of the Loader object;...
  • Page 177 Within an on() handler attached to a button refers to the Timeline that contains the this button, as shown in the following code: // Attached to button on main Timeline on(press) { trace(this); // displays '_level0' Scope of the this keyword...
  • Page 178 Chapter 5: Handling Events...
  • Page 179: Chapter 6: Creating Interaction With Actionscript

    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.
  • Page 180: Controlling Swf File Playback

    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: • functions send the playhead to a frame or scene. gotoAndPlay() gotoAndStop() These are global functions that you can call from any script. You can also use the methods to navigate the MovieClip.gotoAndPlay() MovieClip.gotoAndStop()
  • Page 181 HTML anchor ) tag. <a></a> For example, the following code opens the macromedia.com home page in a blank browser window when the user clicks the button instance named homepage_btn //Attach to frame homepage_btn.onRelease = function () {...
  • Page 182: Creating Interactivity And Visual Effects

    The following code then loads addUser.cfm into a blank browser window and passes to the CFM page in the header: variables_mc.name variables_mc.age POST variables_mc.getURL("addUser.cfm", "_blank", "POST"); For more information, see in Flash ActionScript Language Reference. getURL() Creating interactivity and visual effects To create interactivity and other visual effects, you need to understand the following techniques: •...
  • Page 183 method hides the pointer when the movie clip first appears on the Stage; Mouse.hide() function positions the custom pointer at the same place as the pointer and onMouseMove calls whenever the user moves the mouse. updateAfterEvent function immediately refreshes the screen after the specified event updateAfterEvent occurs, rather than when the next frame is drawn, which is the default behavior.
  • Page 184 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: Create two dynamic text fields, and name them box1_txt and box2_txt. Add labels for the text boxes: X position and Y position, respectively. Select Window >...
  • Page 185 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.
  • Page 186 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.
  • Page 187 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"; 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.
  • Page 188 To create a Color object that targets the movie clip, add the following code to the car_mc Actions panel: var myColor_color:Color = new Color(car_mc); To make the red button change the color of the movie clip to red, add the following carColor code to the Actions panel: red_btn.onRelease = function() {...
  • Page 189 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 method attachSound() 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.
  • Page 190 The following procedures show how to create sound controls similar to the ones shown in the figure. To attach a sound to a Timeline: Select File > Import to import a sound. Select the sound in the library, right-click (Windows) or Control-click (Macintosh), and select Linkage.
  • Page 191 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; parameters , and are variables set in a clip action. startDrag() left right bottom Select Control >...
  • Page 192 Detecting collisions method of the MovieClip class detects collisions in a SWF file. It checks to see if hitTest() an object has collided with a movie clip and returns a Boolean value ( true 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.
  • Page 193 To detect a collision between a movie clip and a point on the Stage: Create a new movie clip on the Stage, and enter as the instance name in the box_mc Property inspector. Select the first frame on Layer 1 in the Timeline. Select Window >...
  • Page 194 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.
  • Page 195: Deconstructing A Sample Script

    mouseListener.onMouseUp = function() { isDrawing = false; Mouse.addListener(mouseListener); 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.
  • Page 196 if (zapped) { bug_mc._y += 25; The bug’s instance name is , and the outlet’s instance name is . In the script, bug_mc zapper_mc the bug is referred to as because the script is attached to the bug and the reserved word this this refers to the object that contains it.
  • Page 197: Chapter 7: Using The Built-In Classes

    “Core classes” on page 199. The rest of the built-in ActionScript classes are specific to Macromedia Flash and the Flash Player object model. Examples of these classes are the Camera, MovieClip, and LoadVars classes. For a complete list, see “Classes specific to Flash Player”...
  • Page 198 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 operator to invoke the class’s constructor function.
  • Page 199: Overview Of Built-In Classes

    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.
  • Page 200 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 . See “Math class”in Math.method(parameter) Math.constant Flash ActionScript Language Reference.
  • Page 201 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...
  • Page 202 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. Class Description Accessibility The Accessibility class manages communication between SWF files and screen reader applications.
  • Page 203 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.
  • Page 204 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 name- value pairs.
  • Page 205: Chapter 8: Working With Movie Clips

    In this way, movie clips provide the foundation of component-based architecture in Macromedia Flash MX 2004 and Macromedia Flash MX Professional 2004. In fact, the components available in the Components panel (Window >...
  • Page 206: Calling Multiple Methods On A Single Movie Clip

    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.
  • Page 207: Loading And Unloading Additional Swf Files

    statement takes a movie clip as a parameter. The object you specify is added to the end with of the current target path. All actions nested inside a statement are carried out inside the with new target path, or scope. For example, in the following script, the statement is passed the with object...
  • Page 208: Specifying A Root Timeline For Loaded Swf Files

    • 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.
  • Page 209: Loading Jpeg Files Into Movie Clips

    This step ensures that any references to in contents.swf—or any SWF file loaded into _root —will refer to its own Timeline, not the actual root Timeline of container.swf. Now target_mc when you click the button, " " 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;...
  • Page 210: Dragging Movie Clips

    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 property on the current level’s Timeline and _xmouse sets the property of the instance to that value: my_mc this.onEnterFrame = function() { my_mc._x = this._xmouse;...
  • Page 211: Creating Movie Clips At Runtime

    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 •...
  • Page 212 in Flash ActionScript Language For more information, see MovieClip.createEmptyMovieClip() Reference. Duplicating or removing a movie clip To duplicate or remove movie clip instances, use the duplicateMovieClip() global functions, or the MovieClip class methods of the same name. The removeMovieClip() method creates a new instance of an existing movie clip instance, assigns duplicateMovieClip() it a new instance name, and gives it a depth, or z-order.
  • Page 213: Adding Parameters To Dynamically Created Movie Clips

    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.
  • Page 214 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]) parameter specifies the name of the object whose parameters you want to use to initObject populate the dynamically created movie clip.
  • Page 215: Managing Movie Clip Depths

    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() , or...
  • Page 216: Drawing Shapes With Actionscript

    In this case, the variable named contains the value 11 because that’s the next highest nextDepth 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...
  • Page 217: Using Movie Clips As Masks

    You can use movie clips with drawing methods as masks; however, as with all movie clip masks, strokes are ignored. To draw a shape: to create an empty movie clip on the Stage. MovieClip.createEmptyMovieClip() 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);...
  • Page 218: About Masking Device Fonts

    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.
  • Page 219: Initializing Class Properties

    Save the document as MoveRight.as in the BallTest directory. To assign the class to a movie clip symbol: In Flash, select File > New, select Flash Document from the list of file types, and click OK. Using the Oval tool, draw a circle on the Stage. Select the circle, and select Modify >...
  • Page 220 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 , moves 50 pixels each time it is clicked; the second, named ball50_mc ball125_mc moves 125 pixels each time its clicked.
  • Page 221: Chapter 9: Working With Text

    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.
  • Page 222 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.
  • Page 223: Creating Text Fields At Runtime

    However, you can’t use the variable name to set the text field’s property. You mytextVar text 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";...
  • Page 224: Using The Textformat Class

    Language Reference. To format a text field with the TextFormat class: In a new Macromedia Flash document, create a text field on the Stage using the Text tool. Type some text in the text field on the Stage, such as “Bold, italic, 24 point text”...
  • Page 225 Apply the TextFormat object to the text field you created in step 1 using TextField.setTextFormat() myText_txt.setTextFormat(txtfmt); This version of applies the specified formatting to the entire text field. setTextFormat() There are two other versions of this method that let you apply formatting to individual characters or groups of characters.
  • Page 226: Formatting Text With Cascading Style Sheets

    Getting text metric information You can use the method to obtain detailed text measurements TextFormat.getTextExtent() 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.
  • Page 227 • “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/...
  • Page 228 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();...
  • Page 229 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.
  • Page 230 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 property. styleSheet textObj_txt.styleSheet = styleSheetObj; Note: Do not confuse the property with the TextField.StyleSheet class. The TextField.styleSheet capitalization indicates the difference.
  • Page 231 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.
  • Page 232 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 Affects all tags. <p> body Affects all tags. The style, if specified, takes precedence over the <body>...
  • Page 233 Create a new text file in a text or XML editor, and save the document as myText.txt. Add the following text to the file: <p class='headline'>Flash Player now supports Cascading StyleSheets!</ p><p><span class='byline'>San Francisco, CA</span>--Macromedia Inc. announced today a new version of Flash Player that supports Cascading Style Sheet (CSS) text styles. For more information, visit the <a href='http://www.macromedia.com'>Macromedia Flash web site.</a></p>...
  • Page 234 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.
  • Page 235 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”...
  • Page 236: Using Html-Formatted Text

    To create the XML text to assign to the text field, open a text editor and enter the following text into a new document: <story><title>Flash Player now supports CSS</title><mainBody><byline>San Francisco, CA</byline>--Macromedia Inc. announced today a new version of Flash Player that supports Cascading Style Sheets (CSS) text styles. For more information, visit the <a href="http://www.macromedia.com">Macromedia Flash website</a></mainBody></story>...
  • Page 237 SWF file that is loading the page. An example of an absolute reference to a URL is ; an example of a relative reference is http://www.macromedia.com index.html • Specifies the name of the target window where you load the page. Options include target .
  • Page 238 For example, the following HTML code creates the link “Go home,” which opens www.macromedia.com in a new browser window: urlText_txt.htmlText = “<a href=’http://www.macromedia.com’ target=’_blank’>Go home</a>”; You can use the special protocol to cause the link to execute an ActionScript asfunction function in a SWF file instead of opening a URL.
  • Page 239 • Specifies the size of the font, in pixels, as shown in the following example: size myText_txt.htmlText = "<font size=’24’ color=’#0000FF’>This is blue, 24- point text</font>"; You can also use relative point sizes instead of a pixel size, such as +2 or -4. Image tag (<img>) tag lets you embed external JPEG files, SWF files, and movie clips inside text fields <img>...
  • Page 240 Italic tag (<i>) tag displays the tagged text in italics, as shown in the following code: <i> That is very <i>interesting</i>. This code example would render as follows: That is very interesting. An italic typeface must be available for the font used. List item tag (<li>) tag places a bullet in front of the text that it encloses, as shown in the following code: <li>...
  • Page 241 Span tag (<span>) tag is available only for use with CSS text styles. (For more information, see <span> “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 class information on creating text style classes, see “Using style classes”...
  • Page 242 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 = "<b>Name\tAge\tDepartment</b>"; //Creates rows with data var row_1 = "Tim\t32\tFinance"; var row_2 = "Edwin\t46\tMarketing";...
  • Page 243 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 attribute. (For information on defining a linkage identifier, see “Attaching a <img> movie clip symbol to the Stage” on page 212.) For example, the following code inserts a movie clip symbol with the linkage identifier into a dynamic text field with the instance name...
  • Page 244: Creating Scrolling Text

    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: <img> <a> textField.htmlText = "Click the image to return home<a href='home.htm'><img src='home.jpg'></a>";...
  • Page 245 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. Select the Down button on the Stage and type into the Instance Name text box.
  • Page 246 Chapter 9: Working with Text...
  • Page 247: Chapter 10: Creating Custom Classes With Actionscript

    The OOP model provided by ActionScript 2.0 is a “syntactic formalization” of the prototype chaining method used in previous versions of Macromedia Flash to create objects and establish inheritance. With ActionScript 2.0, you can create custom classes and extend Flash’s built-in classes.
  • Page 248: Principles Of Object-Oriented Programming

    This section provides a brief introduction to principles involved in developing object-oriented programs. These principles are described in more depth in the rest of this chapter, along with details on how they are implemented in Macromedia Flash MX 2004 and Macromedia Flash MX Professional 2004.
  • Page 249: Inheritance

    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.
  • Page 250: Using Classes: A Simple Example

    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.
  • Page 251 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).
  • Page 252 To create the properties for the Person class, use the keyword to define two variables named , as shown in the following example: name 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.
  • Page 253 // 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.
  • Page 254: Creating And Using Classes

    To create an instance of the Person class in a Flash document: In Flash, select File > New, select Flash Document from the list of document types, and click OK. 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.
  • Page 255 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”...
  • Page 256 keyword is not required in ActionScript 2.0 class definitions because the compiler this resolves the reference and adds it into the bytecode. However, using can improve your code’s this readability. See “Using the this keyword” on page Creating properties and methods A class’s members consist of properties (variable declarations) and methods (function definitions).
  • Page 257 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;...
  • Page 258 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”...
  • Page 259: Creating Dynamic Classes

    If you don’t place a call to in the constructor function of a subclass, the compiler super() 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.
  • Page 260: Using Packages

    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);...
  • Page 261: Creating And Using Interfaces

    // 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 statement (see the following section). import For more information about the naming conventions for packages, see “Packages”...
  • Page 262 For example, the following code declares an interface named MyInterface that contains two methods, . The first method, , has no parameters and method_1() method_2() method_1() specifies a return type of (meaning it does not return a value). The second method, Void , has a single parameter of type String, and specifies a return type of Boolean.
  • Page 263: Instance And Class Members

    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.
  • Page 264 A common use of class members is the Singleton design pattern. The Singleton design pattern makes sure that a class has only one instance and provides a way of globally accessing the instance. For more information on the Singleton design pattern, see www.macromedia.com/devnet/mx/ coldfusion/articles/design_patterns.html. Chapter 10: Creating Custom Classes with ActionScript 2.0...
  • Page 265 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.
  • Page 266 variable is declared as static, so it initializes to 0 only once. Each time the widgetCount Widget class’s constructor function is called, it adds 1 to and then shows the widgetCount number of the current instance that’s being created. Save your file as Widget.as. Create a new FLA document, and save it as createWidget.fla in the same directory as Widget.as.
  • Page 267: Implicit Getter/Setter Methods

    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;...
  • Page 268: Understanding The Classpath

    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.
  • Page 269 • (Windows 2000 or Windows XP) \Documents and Settings\user\Local Settings\ Application Data\Macromedia\Flash MX 2004\language\Configuration\Classes • (Windows 98) \Windows\Application Data\Macromedia\Flash MX 2004\ language\ Configuration\Classes • (Macintosh OS X) Hard Drive/Users/Library/Application Support/Macromedia/ Flash MX 2004/language/Configuration/Classes Note: Do not delete the absolute global classpath. Flash uses this classpath to access built-in classes.
  • Page 270 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 document- level classpath setting, you use the Publish Settings dialog box for the FLA file.
  • Page 271: Importing Classes

    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.
  • Page 272: Compiling And Exporting Classes

    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(); statement applies only to the current script (frame or object) in which it’s called. If import 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...
  • Page 273: Excluding Classes

    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.
  • Page 274 Chapter 10: Creating Custom Classes with ActionScript 2.0...
  • Page 275: Chapter 11: Working With External Data

    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. You can also create persistent TCP/IP socket connections for applications that require low latency—for...
  • Page 276 . In the file myData.txt, you would have text similar to the following example: myData.txt lastSiteVisited=www.macromedia.com But if you used the following code, you could not trace the data that is loading: loadVariables("myData.txt", 0); trace(lastSiteVisited); Each function or method has a specific technique you can use to check data it has loaded. If you...
  • Page 277 For example, the following ActionScript loads the variables from the file into the myData.txt movie clip . An handler assigned to the instance uses loadTarget_mc onData() loadTarget_mc the variable , which is loaded from the file . The following trace lastSiteVisited myData.txt actions appear only after all the variables, including...
  • Page 278 ). For example, the following phrase defines several variables: highScore1=54000&playerName1=RGoulet&highScore2=53455&playerName2= WNewton&highScore3=42885&playerName3=TJones Note: You might need to URL-encode certain characters, such as the plus (+) or ampersand (&) characters. For more information, see www.macromedia.com/support/flash/ts/documents/ url_encoding.htm. For more information, see “Using the LoadVars class” on page 278. Also, see...
  • Page 279 Note: You must have ColdFusion installed on your web server for this example. To load data with the LoadVars object: Create a CFM file in Macromedia Dreamweaver or in your favorite text editor. Add the following text to the file: <cfif IsDefined("Form")>...
  • Page 280 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 ( ) to the SWF file called which appears in the true false...
  • Page 281 The following XML class methods send and load XML data to a server by using the HTTP method: POST • method downloads XML from a URL and places it in an ActionScript load() XML object. • method encodes the XML object into an XML document and sends it to a send() specified URL using the method.
  • Page 282 //(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.”);...
  • Page 283 Flash ActionScript Language Reference. else Note: This design is only an example, and Macromedia can make no claims about the level of security it provides. If you are implementing a secure password-protected system, make sure you have a good understanding of network security.
  • Page 284 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.
  • Page 285: Sending Messages To And From Flash Player

    Sending messages to and from Flash Player To send messages from a SWF file to its host environment (for example, a web browser, a Macromedia Director movie, or the stand-alone Flash Player), you can use the fscommand() function. This function lets you extend your SWF file by using the capabilities of the host. For...
  • Page 286 Insert a new layer on the Timeline, and rename it Actions. Select Frame 1 of the Actions layer, and add the following ActionScript in the Actions panel: window_btn.onRelease = function() { fscommand("popup", "http://www.macromedia.com/"); alert_btn.onRelease = function() { fscommand("alert", "You clicked the button.");...
  • Page 287 In a web browser, open the HTML file to view it. Click the Open Window button; a window opens to the Macromedia website. Click the Alert button; an alert window opens. function can send messages to Macromedia Director that are interpreted by fscommand() Lingo as strings, events, or executable Lingo code.
  • Page 288: Flash Player Security Features

    (non-HTTPS) protocols cannot access content loaded through a secure (HTTPS) protocol, even when both are in exactly the same domain. For example, a SWF file located at http://www.macromedia.com/main.swf cannot load data from https://www.macromedia.com/data.txt without explicit permission; neither can a SWF file served from one domain load data (using , for example) from another domain.
  • Page 289 LocalConnection.allowDomain System.security.allowDomain() For example, suppose main.swf is served from www.macromedia.com. That SWF file then loads another SWF file (data.swf ) from data.macromedia.com into a movie clip instance that’s created dynamically using createEmptyMovieClip // In macromedia.swf this.createEmptyMovieClip("target_mc", this.getNextHighestDepth());...
  • Page 290 Now the function in the loaded SWF file can be called by the macromedia.swf file. getData Notice that permits any SWF file in the allowed domain to script any other SWF allowDomain file in the domain permitting the access, unless the SWF file being accessed is hosted on a site using a secure protocol (HTTPS).
  • Page 291 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.
  • Page 292 A policy file that contains no tags has the same effect as not having a <allow-access-from> 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.
  • Page 293 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.
  • Page 294 For example, in Flash Player 6, a SWF file that resides in www.macromedia.com could access data on a server located at data.macromedia.com. That is, Flash Player 6 allowed a SWF file from one domain to load data from a “similar” domain.
  • Page 295: Chapter 12: Working With External Media

    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.
  • Page 296: Loading External Swf And Jpeg Files

    To play back an external MPEG Layer 3 (MP3) file, use the method of the Sound loadSound() 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.
  • Page 297: Loading External Mp3 Files

    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 , and loadMovie() loadMovieNum() in Flash ActionScript Language Reference. MovieClip.loadMovie() 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 specifies or returns a reference to the root Timeline of a SWF...
  • Page 298: Reading Id3 Tags In Mp3 Files

    In most cases, set the parameter to , especially if you’re loading large sound isStreaming true 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 false...
  • Page 299: Playing Back External Flv Files Dynamically

    You can create FLV files by importing video into the Flash authoring tool and exporting it as an FLV file. (See “Macromedia Flash Video (FLV)” in Using Flash.) If you have Flash Professional, you can use the FLV Export plug-in to export FLV files from supported video-editing applications.
  • Page 300: Preloading External Media

    To play back an external FLV file in a Flash document: 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. Drag a video object from the Library panel onto the Stage;...
  • Page 301 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. Using a MovieClipLoader object to preload SWF and JPEG files involves the following steps: Create a new MovieClipLoader object You can use a single MovieClipLoader object to track...
  • Page 302 To display download progress using the ProgressBar component: In a new Flash document, create a movie clip on the Stage and give it an instance name target_mc Open the Components panel (Window > Development Panels > Components). Drag a ProgressBar component from the Components panel to the Stage. In the Property inspector, give the ProgressBar component the name and, on the pBar...
  • Page 303 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.
  • Page 304 Chapter 12: Working with External Media...
  • Page 305: Appendix A Error Messages

    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:...
  • Page 306 Error number Message text 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.
  • Page 307 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.
  • Page 308 Error number Message text 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.
  • Page 309 Error number Message text 1198 The member function ‘<classname>’ has a different case from the name of the class being defined, ‘<ClassName>’, 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.
  • Page 310 Appendix A: Error Messages...
  • Page 311: Appendix B: Deprecated Flash 4 Operators

    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. Operator Description Associativity Logical NOT Right to left Logical AND Left to right Logical OR (Flash 4)
  • Page 312 Appendix B: Deprecated Flash 4 operators...
  • Page 313: Appendix C: Keyboard Keys And Key Code Values

    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” •...
  • Page 314: Keys On The Numeric Keypad

    Letter or number key Key code 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: Numeric keypad key Key code Numbpad 0 Numbpad 1...
  • Page 315: Function Keys

    Numeric keypad key Key code Numbpad 5 Numbpad 6 Numbpad 7 Numbpad 8 Numbpad 9 Multiply Enter Subtract Decimal Divide 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 This key is reserved by the system and cannot be used in ActionScript.
  • Page 316: Other Keys

    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: Key code Backspace Clear Enter Shift...
  • Page 317 Key code " ' Other keys...
  • Page 318 Appendix C: Keyboard Keys and Key Code Values...
  • Page 319: Appendix D: Writing Scripts For Earlier Versions Of Flash Player

    This chapter provides guidelines to help you write scripts that are syntactically correct for the player version you are targeting. Note: You can review surveys for Flash Player version penetration on the Macromedia website; see www.macromedia.com/software/player_census/flashplayer/. About targeting older versions of Flash Player...
  • Page 320: Using Flash Mx 2004 To Create Content For Flash Player 4

    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.
  • Page 321 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 function is inserted around all operands to these Number() operators.
  • Page 322 Appendix D: Writing Scripts for Earlier Versions of Flash Player...
  • Page 323: Appendix E: Object-Oriented Programming With Actionscript 1

    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: •...
  • Page 324 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, ) and all _height...
  • Page 325 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 inside the this body of the constructor function to refer to the object that the constructor creates;...
  • Page 326 To assign a method to a custom object: Define the constructor function Circle() function Circle(radius) { this.radius = radius; Define the method of the Circle object. The method calculates the area getArea() getArea() of the circle. In the following example, you can use a function literal to define the getArea() method and assign the property to the circle’s prototype object:...
  • Page 327 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() method. If you want these movie clips to have access to the methods duplicateMovieClip() and properties of the built-in MovieClip object, you need to make the new class inherit from the MovieClip class.
  • Page 328 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. For example, reflecting the real world, Bike would be a superclass and MountainBike and Tricycle would be subclasses of the superclass.
  • Page 329 Instead of adding to the MountainBike class and the Tricycle class, you can create the roll() MountainBike class with Bike as its superclass, as shown in the following example: MountainBike.prototype = new Bike(); Now you can call the method of MountainBike, as shown in the following example: roll() var myKona = new MountainBike(20, "teal");...
  • Page 330 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 methods of the Function object. Every function call() apply() in ActionScript is represented by a Function object, so all functions support call() .
  • Page 331 in Flash ActionScript Language Reference. For more information, see Function.apply() 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 specifies the object to which is applied.
  • Page 332 Appendix E: Object-Oriented Programming with ActionScript 1...
  • Page 333: Index

    INDEX ASO files 272 assignment operators accessing object properties 56 about 55 actions compound 55 coding standards 83 different from equality operators 54 repeating 59 associativity, of operators 49 Actions panel 140 asynchronous actions 276 Actions toolbox 141 attaching, sounds 190 yellow items in 144 ActionScript comparing versions 84...
  • Page 334 extending at runtime 259 getter/setter methods 267 calling methods 37 importing 271 capturing keypresses 184 initializing properties at runtime 219 cascading style sheets initializing properties inline 257 and TextField.StyleSheet class 228 instance members and class members 263 applying style classes 231 interfaces 261, 262, 263 applying to text fields 230 naming 255...
  • Page 335 reserved words 75 null 39 variable names 70 Number 36 coding standards 82 Object 37 organizing scripts 82 strictly typing 41 collisions, detecting 192 String 35 between movie clip and Stage point 193 undefined 39 between movie clips 193 data, external 275 colors access between cross-domain SWFs 289, 292 in Actions toolbox 144...
  • Page 336 dot operators 56 defined 25 dot syntax 29 manipulating values in 49 dragging movie clips 210 Extensible Markup Language. See XML drawing external class files lines and fills 194 creating 251 shapes 216 using classpaths to locate 268 duplicating, movie clips 212 external media 66, 295–303 dynamic classes 259 loading MP3 files 297...
  • Page 337 best practices 98 images built-in 60 embedding in text fields 242 calling 63 loading into movie clips 209 coding conventions 72 See also external media constructor 324 importing conversion 35 classes 271 custom 61 scripts, and language encoding 152 defining 61 indentation in code, enabling 152 for controlling movie clips 206 information, passing between SWF files 275...
  • Page 338 ASCII Macromedia Director, communicating with 287 function keys 315 manipulating numbers 36 getting 184 masks 217 letter and number keys 313 and device fonts 218 numeric keypad 314 strokes ignored 217 other keys 316 message box, displaying 286...
  • Page 339 loading SWF files and JPEG files into 296 looping through children 60 object properties managing depth 215 accessing 56 methods 206 assigning values to 198 methods and functions compared 205 object-oriented programming 248 methods, using to draw shapes 216 See also classes nested, defined 205 objects parent, defined 205...
  • Page 340 packages 260 readability, formatting code 81 coding conventions 73 reference data types 34 naming 260 registration point, and loaded images 209 parameters remote defined 27 debugging 155 in parentheses 31 files, communicating with 275 passing to functions 62 sites, continuous connection 284 parent movie clips, defined 205 removing parentheses 31...
  • Page 341 scrolling text 244 subclasses security 288–294 and class members 266 and policy files 290 creating 258 and porting scripts to Flash Player 7 15, 18, 19 creating for movie clips 218 data access across domains 289, 290 suffixes 145 loadPolicyFile 292, 293 formatting code 78 semicolon 31 recommended 80...
  • Page 342 Test Movie and keyboard controls 153 undefined data type 39 and Unicode 153 Unicode testing. See debugging and Test Movie command 152, 153 text support 152 assigning to text field at runtime 222 URL-encoded format, sending information 276 determining required size of TextField object 226 user event, defined 167 encoding 153 UTF-8 (Unicode) 152...
  • Page 343 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 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...
  • Page 344 Index...

This manual is also suitable for:

Flash mx 2004 - actionscript

Table of Contents