background image

182

Chapter 5:  ActionScript Core Language Elements

isFinite()

Availability

Flash Player 5.

Usage

isFinite(

expression:Object

: Boolean

Parameters

expression

  A Boolean value, variable, or other expression to be evaluated.

Returns

A Boolean value.

Description

Function; evaluates 

expression

 and returns 

true

 if it is a finite number or 

false

 if it is infinity 

or negative infinity. The presence of infinity or negative infinity indicates a mathematical error 
condition such as division by 0.

Example

The following example shows return values for 

isFinite

:

isFinite(56)
// returns true

isFinite(Number.POSITIVE_INFINITY)
// returns false 

CHAPTER 5

ActionScript Core Language Elements

Summary of Contents for FLEX

Page 1: ...Flex ActionScript Language Reference ...

Page 2: ... 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 or other entities and may be registered in certain jurisdictions including internationally Third Party Information This guide contains links to third party websites that are not under the control of Macromedia and Ma...

Page 3: ...t data types 18 Assigning data types to elements 23 About variables 27 Using operators to manipulate values in expressions 31 Using condition statements 39 Using built in functions 41 Creating functions 41 CHAPTER 2 Creating Custom Classes with ActionScript 2 0 45 Principles of object oriented programming 45 Using classes a simple example 48 Creating and using classes 51 Creating dynamic classes 5...

Page 4: ...entry for most ActionScript elements 77 Sample entry for classes 78 CHAPTER 5 ActionScript Core Language Elements 80 CHAPTER 6 ActionScript Core Classes 232 CHAPTER 7 ActionScript for Flash 490 APPENDIX A Deprecated Flash 4 operators 809 APPENDIX B Keyboard Keys and Key Code Values 811 Letters A to Z and standard numbers 0 to 9 811 Keys on the numeric keypad 813 Function keys 813 Other keys 814 IN...

Page 5: ...details on the syntax and usage of every language element The following list summarizes the contents of this manual Chapter 1 ActionScript Basics on page 9 describes the terminology and basic concepts used in the rest of the manual Chapter 2 Creating Custom Classes with ActionScript 2 0 on page 45 describes how to create custom classes and objects for manipulating data in your applications Chapter...

Page 6: ...n The user refers to the person who is running your scripts and applications Compile time is the time at which you publish export test or debug your document Runtime is the time at which your script is running in Flash Player ActionScript terms such as method and object are defined in Chapter 1 ActionScript Basics on page 9 Additional resources Specific documentation about Macromedia Flash and rel...

Page 7: ...ng the ActionScript language For information on the classes and language elements you can use in your scripts see Part II Reference Chapter 1 ActionScript Basics 9 Chapter 2 Creating Custom Classes with ActionScript 2 0 45 Chapter 3 Working with External Data 67 PART I ...

Page 8: ......

Page 9: ...s for the rules for a specific term see its entry in Part II Reference Applying the basics of ActionScript in a way that creates elegant programs can be a challenge for users who are new to ActionScript This section contains the following topics Differences between ActionScript and JavaScript on page 10 Terminology on page 11 Syntax on page 13 About data types on page 18 Assigning data types to el...

Page 10: ... Java language but are useful for understanding concepts that you can apply to ActionScript Some of the differences between ActionScript and JavaScript are described in the following list ActionScript does not support browser specific objects such as Document Window and Anchor ActionScript does not completely support all the JavaScript built in objects ActionScript does not support some JavaScript...

Page 11: ...onstructor functions for the built in Array class and the custom Circle class var my_array Array new Array var my_circle Circle new Circle 9 Data types describe the kind of information a variable or ActionScript element can contain The built in ActionScript data types are String Number Boolean Object MovieClip Function null and undefined For more information see About data types on page 18 Events ...

Page 12: ...ist of keywords see Keywords and reserved words on page 17 Methods are functions associated with a class For example sortOn is a built in method associated with the Array class You can also create functions that act as methods either for objects based on built in classes or for objects based on classes that you create For example in the following code clear becomes a method of a controller object ...

Page 13: ...ructure for ActionScript statements Target paths are hierarchical addresses of movie clip instance names variables and objects in a SWF file You can use a target path to direct an action at a movie clip or to get or set the value of a variable or property For example the following statement is the target path to the volume property of the object named stereoControl stereoControl volume Variables a...

Page 14: ...rsion of Flash Player you should review both external script files and scripts in FLA files to confirm that you used consistent capitalization Case sensitivity is implemented on a per movie basis If a strict Flash Player 7 application calls a non strict Flash Player 6 movie ActionScript executed in the latter movie is non strict For example if you use loadMovie to load a Flash Player 6 SWF into a ...

Page 15: ...ate getMonth Class Circle as class Circle radius Function circleArea function radius Number return radius radius Math PI The following examples show code with opening brace on the next line Event handler my_btn onRelease function var myDate Date new Date var currentMonth Number myDate getMonth Class Square as class Square side Function squareArea function side Number return side side Semicolons An...

Page 16: ...ment the parentheses cause new Color this to evaluate and create a Color object new Color this setRGB 0xffffff If you don t use parentheses you must add a statement to evaluate the expression as shown in the following example myColor new Color this myColor setRGB 0xffffff Comments Using comments to add notes to scripts is highly recommended Comments are useful for tracking what you intended and fo...

Page 17: ...r x Number 15 var y Number 20 The following code doesn t run create new Date object var myDate Date new Date var currentMonth Number myDate getMonth convert month number to month name var monthName String calcMonth currentMonth var year Number myDate getFullYear var currentDate Number myDate getDate The code below runs var name String My name is var age Number 20 Keywords and reserved words Action...

Page 18: ... on page 23 Void data type on page 23 ActionScript also has built in classes such as Array and Date that can be considered complex data types If you are an advanced developer you might create custom classes Any class that you define using the class declaration is also considered a data type Variables containing primitive data types behave differently in certain situations than those containing ref...

Page 19: ...not be represented in ActionScript except by special escape sequences The following table provides all the ActionScript escape characters Strings in ActionScript are immutable the same as Java Any operation that modifies a string returns a new string The String class is a built in ActionScript class Number data type The number data type is a double precision floating point number The minimum value...

Page 20: ... to control the flow of a script The following example checks that users enter values into two TextInput component instances Two Boolean variables are created userNameEntered and isPasswordCorrect and if both variables evaluate to true a welcome message is assigned to the titleMessage String variable Add two TextInput components and one Button component on the Stage Strict data type the three comp...

Page 21: ... called user and creates three properties name age and phone which are String and Numeric data types var user Object new Object user name Irving user age 32 user phone 555 1234 For more information see Using classes a simple example on page 48 MovieClip data type Movie clips are symbols that can play animation in a Flash application They are the only data type that refers to a graphic element The ...

Page 22: ...le 1 0x000000 100 square_mc beginFill 0xFF0000 100 square_mc moveTo 100 100 square_mc lineTo 200 100 square_mc lineTo 200 200 square_mc lineTo 100 200 square_mc lineTo 100 100 square_mc endFill square_mc onPress function this startDrag square_mc onRelease function this stopDrag The MovieClip class is the base class for Flex components Although Macromedia supports some of the MovieClip interface fo...

Page 23: ...le frames the code does not execute a second time because the init variable is no longer undefined Void data type The void data type has one value void and is used in a function definition to indicate that the function does not return a value as shown in the following example Creates a function with a return type Void function displayFromURL url String Void Assigning data types to elements At runt...

Page 24: ... data types as needed in the following example when used with a string the addition operator expects the other operand to be a string Next in line number 7 ActionScript converts the number 7 to the string 7 and adds it to the end of the first string resulting in the following string Next in line number 7 Strict data typing is recommended for more information see Strict data typing on page 24 Stric...

Page 25: ...atch errors at compile time For example suppose you type the following code in the Student as class file class Student var status Boolean property of Student objects in a script var studentMaryLago Student new Student studentMaryLago status enrolled When Flash compiles this script a Type mismatch error is generated because the SWF file is expecting a Boolean value Using strict typing also helps to...

Page 26: ...ark myAnimal Animal var foo Dog Dog myAnimal if foo foo bark You can cast an expression to an interface If the expression is an object that implements the interface or has a base class that implements the interface the cast succeeds If not the cast fails Casting to null or undefined returns undefined You can t override primitive data types that have a corresponding global conversion function with ...

Page 27: ...referenced Initializing a variable helps you track and compare the variable s value as the SWF file plays Variables can hold any type of data see About data types on page 18 The type of data a variable contains affects how the variable s value changes when it is assigned in a script Typical types of information that you can store in a variable include a URL a user s name the result of a mathematic...

Page 28: ...iable scopes For more information see Controlling member access on page 53 and Creating class members on page 60 Local variables To declare local variables use the var statement inside the body of a function A local variable declared within a function block is defined within the scope of the function block and expires at the end of the function block For example the variables i and j are often use...

Page 29: ...er 2 counter local variable trace counter accesses local variable and displays 0 through 2 count trace counter accesses global variable and displays 100 This example simply shows that the global variable is not accessed in the scope of the count function To avoid confusion in your applications name your variables uniquely The Flash Player version 7 and later security sandbox enforces restrictions ...

Page 30: ...Number x x return x var inValue Number 3 var out Number sqr inValue trace inValue 3 trace out 9 The value of the variable inValue does not change even though the value of x in the function changes The object data type can contain such a large amount of complex information that a variable with this type doesn t hold an actual value it holds a reference to a value This reference is similar to an ali...

Page 31: ... calling a function Operators are characters that specify how to combine compare or modify the values of an expression The elements that the operator performs on are called operands For example in the following statement the addition operator adds the value of a numeric literal to the value of the variable foo foo and 3 are the operands foo 3 This section describes general rules about common types...

Page 32: ...s the order in which they are performed Associativity can be either left to right or right to left For example the multiplication operator has an associativity of left to right therefore the following two statements are equivalent total 2 3 4 total 2 3 4 The following table lists all the ActionScript operators and their associativity from highest to lowest precedence Operator Description Associati...

Page 33: ...nus Right to left Bitwise left shift Left to right Bitwise right shift Left to right Bitwise right shift unsigned Left to right instanceof Instance of finds the class of which the object is an instance Requires Flash Player 6 or later Left to right Less than Left to right Less than or equal to Left to right Greater than Left to right Greater than or equal to Left to right Equal Left to right Not e...

Page 34: ...f score 100 highScore else lowScore In the following example if the user s entry a string variable userEntry matches their stored password the playhead moves to a named frame called welcomeUser if userEntry userPassword gotoAndStop welcomeUser Except for the strict equality operator the comparison operators compare strings only if both operands are strings If only one of the operands is a string A...

Page 35: ...or lowercase before comparing them Operator Operation performed Less than Returns true if the left operand is mathematically smaller than the right operand Returns true if the left operand alphabetically precedes the right operand for example a b Greater than Returns true if the left operand is mathematically larger than the right operand Returns true if the left operand alphabetically follows the...

Page 36: ...ill be greater than 50 consider putting the condition i 50 first the condition i 50 will be checked first and the second condition doesn t need to be checked in most cases The following table lists the ActionScript logical operators Bitwise operators Bitwise operators internally manipulate floating point numbers to change them into 32 bit integers The exact operation performed depends on the opera...

Page 37: ... the strict equality operator returns false The strict inequality operator returns the opposite of the strict equality operator The following table lists the ActionScript equality operators Assignment operators You can use the assignment operator to assign a value to a variable as shown in the following example var password String Sk8tEr You can also use the assignment operator to assign multiple ...

Page 38: ...it must be an identifier The following examples use the dot operator year month June year month day 9 The dot operator and the array access operator perform the same role but the dot operator takes an identifier as its property whereas the array access operator evaluates its contents to a name and then accesses the value of that named property For example the following expressions access the same ...

Page 39: ...cally set and retrieve instance names and variables as shown in the following example eval mc i The array access operator can also be used on the left side of an assignment statement This lets you dynamically set instance variable and object names as shown in the following example name index Gary You create multidimensional arrays in ActionScript by constructing an array the elements of which are ...

Page 40: ...pression and executes the code in the body of the loop if the expression is true After each statement in the body is executed the expression is evaluated again You can use the do while statement to create the same kind of loop as a while loop In a do while loop the expression is evaluated at the bottom of the code block so the loop always runs at least once To repeat an action using a built in cou...

Page 41: ...ywhere in a SWF file If you pass values as parameters to a function the function will operate on those values A function can also return values Flash has built in functions that let you access certain information and perform certain tasks such as getting the version number of Flash Player that is hosting the SWF file getVersion Functions that belong to an object are called methods Functions that d...

Page 42: ...tatement You can use a function literal to define a function return its value and assign it to a variable in one expression as shown in the following example area function return Math PI radius radius 5 When a function is redefined the new definition replaces the old definition For information on strictly typing function return types and parameters see Strict data typing on page 24 Passing paramet...

Page 43: ...nction Use the return statement to return values from functions The return statement stops the function and replaces it with the value of the return statement The following rules govern how to use the return statement in functions If you specify a return type other than Void for a function you must include a return statement followed by the returned value in the function If you specify a return ty...

Page 44: ...ry and pass any required parameters inside parentheses For example the following statement invokes the function sqr in the object mathLib passes the parameter 3 to it and stores the result in the variable temp var temp Number mathLib sqr 3 The following example uses an path to call the initialize function that requires no parameters initialize ...

Page 45: ...face and packages that will be familiar to you if you ve programmed with Java Strict data typing ActionScript 2 0 also lets you explicitly specify data types for variables function parameters and function return types For example the following code declares a variable named userName of type String a built in ActionScript data type or class var userName String Compiler warnings and errors The previ...

Page 46: ...are jointly referred to as members of that class The characteristics in the cat example name age and color are called properties of the class and are represented as variables the behaviors eating sleeping are called methods of the class and are represented as functions In ActionScript you define a class with the class statement see Creating and using classes on page 51 Inheritance One of the prima...

Page 47: ...erface that declares the chaseTail and eatCatNip methods A Cat class or any other class could then implement this interface and provide definitions for those methods Unlike Java interfaces ActionScript interfaces exist at runtime which allows type casting For more information see Creating an interface on page 58 Encapsulation In elegant object oriented design objects are seen as black boxes that c...

Page 48: ...s in another script or creating a subclass based on the original class This section also discusses a feature in ActionScript 2 0 called strict data typing which lets you specify the data type for a variable function parameter or function return type Although this section discusses only classes the general workflow is the same for using interfaces For more information see Creating and using interfa...

Page 49: ...operties are defined at the top of the class body which makes the code easier to understand but this isn t required The colon syntax var age Number and var name String used in the variable declarations is an example of strict data typing When you type a variable in this way var variableName variableType the ActionScript 2 0 compiler ensures that any values assigned to that variable match the speci...

Page 50: ...String return Hello my name is this name and I m this age years old This code is the completed code for this class The return value of the getInfo function is strictly typed optional but recommended as a string 8 Save the file You ve successfully created a class file To continued with this example see Creating an instance of the Person class on page 50 Creating an instance of the Person class The ...

Page 51: ...es in more detail Creating and using classes As discussed in Using classes a simple example on page 48 a class consists of two parts the declaration and the body The class declaration consists minimally of the class statement followed by an identifier for the class name then left and right curly braces Everything inside the braces is the class body as shown in the following example class className...

Page 52: ...g classes see the following topics Constructor functions on page 52 Creating properties and methods on page 53 Controlling member access on page 53 Initializing properties inline on page 54 Creating subclasses on page 55 Constructor functions A class s constructor is a special function that is called automatically when you create an instance of a class using the new operator The constructor functi...

Page 53: ...method definition The this keyword is not required in ActionScript 2 0 class definitions because the compiler resolves the reference and adds it into the bytecode However using this can improve your code s readability Controlling member access By default any property or method of a class can be accessed by any other class all members of a class are public by default However in some cases you might...

Page 54: ... or public members The this keyword is not required in ActionScript 2 0 class definitions because the compiler resolves the reference and adds it into the bytecode However using this can improve your code s readability Initializing properties inline You can initialize properties inline that is when you declare them with default values as shown in the following example class Person var age Number 5...

Page 55: ...perties or methods that you have declared to be private using the private keyword For more information on private variables see Controlling member access on page 53 You can extend your own custom classes as well as many of the built in ActionScript classes You cannot extend the TextField class or static classes such as the Math Key and Mouse classes When you extend a built in ActionScript class yo...

Page 56: ...or For example the following code creates a new instance of the Person class a_person and then tries to assign a value to a property named hairColor which doesn t exist var a_person Person new Person a_person hairColor blue compiler error This code causes a compiler error because the Person class doesn t declare a property named hairColor In most cases this is exactly what you want to happen Compi...

Page 57: ...ed subpackages each with its own class files Package names must be identifiers that is the first character must be a letter underscore _ or dollar sign and each subsequent character must be a letter number underscore or dollar sign Packages are commonly used to organize related classes For example you might have three related classes Square Circle and Triangle that are defined in Square as Circle ...

Page 58: ...e methods these classes will use to communicate and then have each class implement provide its own definitions for those methods You can usually program successfully without using interfaces When used appropriately however interfaces can make the design of your applications more elegant scalable and maintainable For more information on creating and using interfaces see the following topics Creatin...

Page 59: ... the interface This is useful for determining if a given object implements a given interface For example consider the following interface interface Movable function moveUp Void function moveDown Void Now consider the class Box which implements the Movable interface class Box implements Movable var xpos Number var ypos Number function moveUp Void trace moving up method definition function moveDown ...

Page 60: ...hown in the following example ClassName classMember For example the ActionScript Math class consists only of static methods and properties To call any of its methods you don t create an instance of the Math class Instead you simply call the methods on the Math class itself The following code calls the sqrt method of the Math class var square_root Number Math sqrt 4 Creating class members All the m...

Page 61: ...on 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 Often there are situations when you need exactly one object of a particular type in a system For example in a chess game there...

Page 62: ... in the Output panel To create an instance counter using a class variable 1 Create a new ActionScript AS file 2 Add the following code to the file class Widget static var widgetCount Number 0 initialize class variable function Widget trace Creating widget widgetCount widgetCount The widgetCount variable is declared as static so it initializes to 0 only once Each time the Widget class s constructor...

Page 63: ...practice discourages direct access to properties within a class Classes typically define getter methods that provide read access and setter methods that provide write access to a given property For example imagine a class that contains a property called userName var userName String Instead of allowing instances of the class to directly access this property obj userName Jody for example the class m...

Page 64: ...nes getter and setter methods named user you could not also have a property named user in the same class Unlike ordinary methods getter setter methods are invoked without any parentheses or arguments For example the following syntax could now be used to access or modify the value of userName with the getter setter methods previously defined var obj LoginClass2 new LoginClass2 RickyM calling get me...

Page 65: ...se a class s abbreviated name rather than its fully qualified name You can also use the wildcard character to import all the classes in a package For example suppose you created a class named UserClass that s included in the package directory path com xyzzycorporation util users In the file com xyzzycorporation util users UserClass as class com xyzzycorporation util users UserClass Suppose that in...

Page 66: ...66 Chapter 2 Creating Custom Classes with ActionScript 2 0 ...

Page 67: ...ng Flex Security in Developing Flex Applications Sending and loading variables to and from a remote source A SWF file is a window for capturing and displaying information much like an HTML page However SWF files can stay loaded in the browser and continuously update with new information without having to reload the entire page Using ActionScript functions and methods you can send information to an...

Page 68: ...eck to see if it has been loaded For example you can t load variables and manipulate their values in the same script because the data to manipulate doesn t exist in the file until it is loaded In the following script you cannot use the variable lastSiteVisited until you re sure that the variable has loaded from the file myData txt In the file myData txt you would have text similar to the following...

Page 69: ...Variables to load them into the SWF file each time someone played the game The function call might look like the following example loadVariables http www mySite com scripts high_score cfm scoreClip GET This example loads variables from the ColdFusion script called high_score cfm into the movie clip instance scoreClip using the GET HTTP method Any variables loaded with the loadVariables function mu...

Page 70: ... onLoad instead of the obsolete deprecated onClipEvent data approach required for loadVariables There are error notifications You can add custom HTTP request headers You must create a LoadVars object to call its methods This object is a container to hold the loaded data For more information see the LoadVars class entry About XML Extensible Markup Language XML is becoming the standard for exchangin...

Page 71: ...s ActionScript provides a built in XMLSocket class which lets you open a continuous connection with a server A socket connection lets the server publish or push information to the client as soon as that information is available Without a continuous connection the server must wait for an HTTP request This open connection removes latency issues and is commonly used for real time applications such as...

Page 72: ...alhost 12345 displays text regarding connection theSocket onConnect function myStatus if myStatus conn_txt text connection successful else conn_txt text no connection made data to send function sendData var myXML XML new XML var mySend myXML createElement thenode mySend attributes myData someData myXML appendChild mySend theSocket send myXML button sends data sendButton onRelease function sendData...

Page 73: ...g table shows the values you can specify for the command and arguments parameters of fscommand to control the playback and appearance of a SWF file playing in the stand alone player including projectors A projector is a SWF file saved in a format that can run as a stand alone application that is embedding Flash Player with your content in an executable file To use fscommand to send a message to a ...

Page 74: ... sends a VB event with two strings that can be handled in the environment s programming language For more information use the keywords Flash method to search the Flash Support Center at www macromedia com support flash About using JavaScript to control Flash applications Flash Player 6 6 0 40 0 and later supports certain JavaScript methods that are specific to Flash applications as well as FSComma...

Page 75: ...eview as you write your scripts For an overview of how to use ActionScript see Part I Welcome to ActionScript Chapter 4 About the ActionScript Language Reference 77 Chapter 5 ActionScript Core Language Elements 80 Chapter 6 ActionScript Core Classes 232 Chapter 7 ActionScript for Flash 490 Appendix A Deprecated Flash 4 operators 809 Appendix B Keyboard Keys and Key Code Values 811 PART II ...

Page 76: ......

Page 77: ...r Flash on page 490 describes functions properties and classes of Macromedia Flash Player that you can use in a Macromedia Flex application if appropriate For additional elements that are available for Flex see Flex ActionScript and MXML API Reference Use the information in the sample entries to interpret the structure and conventions used in these types of entries To use examples in a script copy...

Page 78: ...classes are listed in Chapter 5 ActionScript Core Language Elements on page 80 Classes that are specific to Flash are listed alphabetically with other Flash language elements in Chapter 7 ActionScript for Flash on page 490 Flex supports the Flash elements however they might not be appropriate in all Flex applications For more information see the description for each element Entry title The entry t...

Page 79: ...Sample entry for classes 79 Method property and event handler listings The methods properties and event handlers of a class are listed alphabetically after the class entry ...

Page 80: ...to a particular Macromedia product That is all products that support ActionScript have access to any language element in this chapter For information on the classes that all Macromedia products support see Chapter 6 ActionScript Core Classes on page 232 For information on additional language elements and classes that Flex supports see Developing Flex Applications ...

Page 81: ...he operator expression subtracts 1 from the expression and returns the initial value of expression the value prior to the subtraction For more information see Operator precedence and associativity on page 32 Example The pre decrement form of the operator decrements x to 2 x 1 2 and returns the result as y var x Number 3 var y Number x y is equal to 2 The post decrement form of the operator decreme...

Page 82: ...xpression and returns the initial value of expression the value prior to the addition The pre increment form of the operator increments x to 2 x 1 2 and returns the result as y var x Number 1 var y Number x trace x x traces x 2 trace y y traces y 2 The post increment form of the operator increments x to 2 x 1 2 and returns the original value of x as the result y var x Number 1 var y Number x trace...

Page 83: ... result to the log file 1 2 3 4 5 6 7 8 9 10 The following example uses as a post increment operator in a while loop using a while loop var a Array var a Array new Array var i Number 0 while i 10 a push i trace a toString traces 0 1 2 3 4 5 6 7 8 9 The following example uses as a post increment operator in a for loop using a for loop var a Array var a Array new Array for var i 0 i 10 i a push i tr...

Page 84: ...of using the logical NOT operator true returns false false returns true For more information see Operator precedence and associativity on page 32 Example In the following example the variable happy is set to false The if condition evaluates the condition happy and if the condition is true the trace statement sends a string to the log file var happy Boolean false if happy trace don t worry be happy...

Page 85: ...ual only if they both refer to the same object array or function Values inside the object array or function are not compared When comparing by value if expression1 and expression2 are different data types ActionScript will attempt to convert the data type of expression2 to match that of expression1 For more information see Automatic data typing on page 24 and Operator precedence and associativity ...

Page 86: ...b Array 1 2 3 trace a 1 2 3 trace b 1 2 3 trace a b true a b trace a 1 2 3 trace b 1 2 3 trace a b false trace statement output 1 2 3 1 2 3 true 1 2 3 1 2 3 false See also logical NOT strict inequality logical AND logical OR equality strict equality strict inequality Availability Flash Player 6 Usage expression1 expression2 Parameters None Returns A Boolean value ...

Page 87: ... and functions are compared by reference A variable is compared by value or by reference depending on its type For more information see Operator precedence and associativity on page 32 Example The comments in the following code show the returned value of operations that use the equality strict equality and strict inequality operators var s1 String 5 var s2 String 5 var s3 String Hello var n Number...

Page 88: ...s the modulo operator trace 12 5 traces 2 trace 4 3 2 1 traces 0 0999999999999996 trace 4 4 traces 0 The first trace returns 2 rather than 12 5 or 2 4 because the modulo operator returns only the remainder The second trace returns 0 0999999999999996 instead of the expected 0 1 because of the limitations of floating point accuracy in binary computing See Also division modulo assignment Availability...

Page 89: ...ficant digits discarded when they are converted so the value is still 32 bit Negative numbers are converted to an unsigned hex value using the two s complement notation with the minimum being 2147483648 or 0x800000000 numbers less than the minimum are converted to two s complement with greater precision and then have the most significant digits discarded as well The return value is interpreted as ...

Page 90: ...cal AND Availability Flash Player 4 Usage expression1 expression2 Parameters None Returns A Boolean value Description Operator logical performs a Boolean operation on the values of one or both of the expressions Evaluates expression1 the expression on the left side of the operator and returns false if the expression evaluates to false If expression1 evaluates to true expression2 the expression on ...

Page 91: ...trace You Win the Game else trace Try Again output You Win the Game See also logical NOT inequality strict inequality logical OR equality strict equality bitwise AND assignment Availability Flash Player 5 Usage expression1 expression2 Parameters None Returns A 32 bit integer the value of expression1 expression2 Description Operator assigns expression1 the value of expression1 expression2 For examp...

Page 92: ...asses them as parameters to a function outside the parentheses Usage 1 Controls the order in which the operators execute in the expression Parentheses override the normal precedence order and cause the expressions within the parentheses to be evaluated first When parentheses are nested the contents of the innermost parentheses are evaluated before the contents of the outer ones Usage 2 Evaluates a...

Page 93: ...ailability Flash Player 4 Usage Negation expression Subtraction expression1 expression2 Parameters None Returns An integer or floating point number Description Operator arithmetic used for negating or subtracting Usage 1 When used for negating it reverses the sign of the numerical expression Usage 2 When used for subtracting it performs an arithmetic subtraction on two numerical expressions subtra...

Page 94: ...y Flash Player 4 Usage expression1 expression2 Parameters None Returns An integer or floating point number Description Operator arithmetic multiplies two numerical expressions If both expressions are integers the product is an integer If either or both expressions are floating point numbers the product is a floating point number For more information see Operator precedence and associativity on pag...

Page 95: ...ing two expressions are equivalent x y x x y For more information see Operator precedence and associativity on page 32 Example Usage 1 The following example assigns the value 50 to the variable x var x Number 5 var y Number 10 trace x y output 50 Usage 2 The second and third lines of the following example calculate the expressions on the right side of the equal sign and assign the results to x and...

Page 96: ...r var v Number 0 v 4 5 6 trace v output 4 The following example uses the comma operator with the parentheses operator and illustrates that the comma operator returns the value of the last expression when used with the parentheses operator var v Number 0 v 4 5 6 trace v output 6 The following example uses the comma operator without the parentheses operator and illustrates that the comma operator se...

Page 97: ...e that is a child of or nested in another movie clip Returns The method property or movie clip named on the right side of the dot Description Operator used to navigate movie clip hierarchies to access nested child movie clips variables or properties The dot operator is also used to test or set the properties of an object or top level class execute a method of an object or top level class or create...

Page 98: ...s operator specifies the variable s type when used in a function declaration or definition this operator specifies the function s return type when used with a function parameter in a function definition this operator specifies the variable type expected for that parameter Types are a compile time only feature All types are checked at compile time and errors are generated when there is a mismatch M...

Page 99: ...Also var function conditional Availability Flash Player 4 Usage expression1 expression2 expression3 Parameters expression1 An expression that evaluates to a Boolean value usually a comparison expression such as x 5 expression2 expression3 Values of any type Returns The value of expression2 or expression3 Description Operator instructs Flash to evaluate expression1 and if the value of expression1 i...

Page 100: ...r 4 Usage expression1 expression2 Parameters expression A number or a variable that evaluates to a number Returns A floating point number Description Operator arithmetic divides expression1 by expression2 The result of the division operation is a double precision floating point number For more information see Operator precedence and associativity on page 32 Example The following statement divides ...

Page 101: ...reter Example The following script uses comment delimiters to identify the first third fifth and seventh lines as comments record the X position of the ball movie clip var ballX Number ball_mc _x record the Y position of the ball movie clip var ballY Number ball_mc _y record the X position of the bat movie clip var batX Number bat_mc _x record the Y position of the ball movie clip var batY Number ...

Page 102: ...will end the comment regardless of the number of opening comment tags placed between them For more information see Operator precedence and associativity on page 32 Example The following script uses comment delimiters at the beginning of the script records the X and Y positions of the ball and bat movie clips var ballX Number ball_mc _x var ballY Number ball_mc _y var batX Number bat_mc _x var batY...

Page 103: ... Also division array access Availability Flash Player 4 Usage myArray a0 a1 aN myArray i value myObject propertyName Parameters myArray The name of an array a0 a1 aN Elements in an array any native type or object instance including nested arrays i An integer index greater than or equal to 0 myObject The name of an object propertyName A string that names a property of the object Returns Usage 1 A r...

Page 104: ...Usage 2 Surround the index of each element with brackets to access it directly you can add a new element to an array or you can change or retrieve the value of an existing element The first index in an array is always 0 as shown in the following example var my_array Array new Array my_array 0 15 my_array 1 Hello my_array 2 true You can use brackets to add a fourth element as shown in the following...

Page 105: ...the following ActionScript to loop over all objects in the _root scope which is useful for debugging for i in _root trace i _root i You can also use the array access operator on the left side of an assignment statement to dynamically set instance variable and object names employee_array 2 Sam See also Array class Object class bitwise XOR Availability Flash Player 5 Usage expression1 expression2 Pa...

Page 106: ...o 2147483647 For more information see Operator precedence and associativity on page 32 Example The following example uses the bitwise XOR operator on the decimals 15 and 9 and assigns the result to the variable x 15 decimal 1111 binary 9 decimal 1001 binary var x Number 15 9 trace x 1111 1001 0110 returns 6 decimal 0110 binary See also bitwise AND bitwise AND assignment bitwise XOR assignment bitw...

Page 107: ... values for each name property Returns Usage 1 An Object object Usage 2 Nothing except when a function has an explicit return statement in which case the return type is specified in the function implementation Description Operator creates a new object and initializes it with the specified name and value property pairs Using this operator is the same as using the new Object syntax and populating th...

Page 108: ...i account i The following example shows how array and object initializers can be nested within each other var person Object name Gina Vechio children Ruby Chickie Puppa The following example uses the information in the previous example and produces the same result using constructor functions var person Object new Object person name Gina Vechio person children new Array person children 0 Ruby perso...

Page 109: ...being 2147483648 or 0x800000000 numbers less than the minimum are converted to two s complement with greater precision and also have the most significant digits discarded The return value is interpreted as a two s complement number with sign so the return value will be an integer in the range 2147483648 to 2147483647 For more information see Operator precedence and associativity on page 32 Example...

Page 110: ...and associativity on page 32 Example The following example uses the logical OR operator in an if statement The second expression evaluates to true so the final result is true var x Number 10 var y Number 250 var start Boolean false if x 25 y 200 start trace the logical OR test passed output the logical OR test passed The message the logical OR test passed appears because one of the conditions in t...

Page 111: ...pression1 expression2 For example the following two statements are equivalent x y x x y For more information see Operator precedence and associativity on page 32 Example The following example uses the bitwise OR assignment operator 15 decimal 1111 binary var x Number 15 9 decimal 1001 binary var y Number 9 1111 1001 1111 trace x y returns 15 decimal 1111 binary See also bitwise AND bitwise AND ass...

Page 112: ...its after the decimal point Positive integers are converted to an unsigned hex value with a maximum value of 4294967295 or 0xFFFFFFFF values larger than the maximum have their most significant digits discarded when they are converted so the value is still 32 bit Negative numbers are converted to an unsigned hex value via the two s complement notation with the minimum being 2147483648 or 0x80000000...

Page 113: ...ber or string Returns A string integer or floating point number Description Operator adds numeric expressions or concatenates combines strings If one expression is a string all other expressions are converted to strings and concatenated If both expressions are integers the sum is an integer if either or both expressions are floating point numbers the sum is a floating point number For more informa...

Page 114: ...ing or a number Description Operator arithmetic compound assignment assigns expression1 the value of expression1 expression2 For example the following two statements have the same result x y x x y This operator also performs string concatenation All the rules of the addition operator apply to the addition assignment operator For more information see Operator precedence and associativity on page 32...

Page 115: ...re evaluated using alphabetical order all capital letters come before lowercase letters For more information see Operator precedence and associativity on page 32 Example The following examples show true and false returns for both numeric and string comparisons trace 3 10 true trace 10 3 false trace Allen Jack true trace Jack Allen false trace 11 3 true trace 11 3 false numeric comparison trace C a...

Page 116: ...000 numbers less than the minimum are converted to two s complement with greater precision and also have the most significant digits discarded The return value is interpreted as a two s complement number with sign so the return value will be an integer in the range 2147483648 to 2147483647 For more information see Operator precedence and associativity on page 32 Example In the following example th...

Page 117: ...n and stores the contents as a result in expression1 The following two expressions are equivalent A B A A B For more information see Operator precedence and associativity on page 32 Example In the following example you use the bitwise left shift and assignment operator to shift all bits one space to the left var x Number 4 shift all bits one slot to the left x 1 trace x output 8 4 decimal 0100 bin...

Page 118: ...r all capital letters come before lowercase letters For more information see Operator precedence and associativity on page 32 Example The following examples show true and false results for both numeric and string comparisons trace 5 10 true trace 2 2 true trace 10 3 false trace Allen Jack true trace Jack Allen false trace 11 3 true trace 11 3 false numeric comparison trace C abc true trace A a tru...

Page 119: ...le uses assignment by reference to create the moonsOfJupiter variable which contains a reference to a newly created Array object Assignment by value is then used to copy the value Callisto to the first element of the array referenced by the variable moonsOfJupiter var moonsOfJupiter Array new Array moonsOfJupiter 0 Callisto The following example uses assignment by reference to create a new object ...

Page 120: ...tements are equivalent x y x x y String expressions must be converted to numbers otherwise NaN not a number is returned For more information see Operator precedence and associativity on page 32 Example The following example uses the subtraction assignment operator to subtract 10 from 5 and assign the result to the variable x var x Number 5 var y Number 10 x y trace x output 5 The following example...

Page 121: ...e equal if they refer to the same object array or function Two separate arrays are never considered equal even if they have the same number of elements When comparing by value if expression1 and expression2 are different data types ActionScript will attempt to convert the data type of expression2 to match that of expression1 For more information see Automatic data typing on page 24 and Operator pr...

Page 122: ...nequality strict inequality logical AND logical OR strict equality strict equality Availability Flash Player 6 Usage expression1 expression2 Returns A Boolean value Description Operator tests two expressions for equality the strict equality operator performs in the same way as the equality operator except that data types are not converted For more information see Automatic data typing on page 24 T...

Page 123: ...lean false trace string1 bool2 true trace string1 bool2 false The following examples show how strict equality treats variables that are references differently than it treats variables that contain literal values This is one reason to consistently use String literals and to avoid the use of the new operator with the String class Create a string variable using a literal value var str String asdf Cre...

Page 124: ...l letters come before lowercase letters For more information see Operator precedence and associativity on page 32 Example In the following example the greater than operator is used to determine whether the value of the text field score_txt is greater than 90 if score_txt text 90 trace Congratulations you win else trace sorry try again greater than or equal to Availability Flash Player 4 Usage expr...

Page 125: ...its on the left are filled in with 0 if the most significant bit the bit farthest to the left of expression1 is 0 and filled in with 1 if the most significant bit is 1 Shifting a value right by one position is the equivalent of dividing by 2 and discarding the remainder Floating point numbers are converted to integers by discarding any digits after the decimal point Positive integers are converted...

Page 126: ...xample shows the result of the previous example var x Number 1 This is because 1 decimal equals 11111111111111111111111111111111 binary thirty two 1 s shifting right by one bit causes the least significant bit farthest to the right to be discarded and the most significant bit to be filled in with 1 The result is 11111111111111111111111111111111 thirty two 1 s binary which represents the 32 bit int...

Page 127: ...t right by one bit to see next bit numberToConvert 1 return result trace convertToBinary 479 Returns the string 00000000000000000000000111011111 This string is the binary representation of the decimal number 479 See also bitwise right shift bitwise unsigned right shift Availability Flash Player 5 Usage expression1 expression2 Parameters expression1 A number or expression to be shifted right expres...

Page 128: ... Number 1 1 trace x output 2147483647 This is because 1 decimal is 11111111111111111111111111111111 binary thirty two 1 s and when you shift right unsigned by 1 bit the least significant rightmost bit is discarded and the most significant leftmost bit is filled with a 0 The result is 01111111111111111111111111111111 binary which represents the 32 bit integer 2147483647 See also bitwise right shift...

Page 129: ...lue is true Note Unlike the Boolean class constructor the Boolean function does not use the keyword new Moreover the Boolean class constructor initializes a Boolean object to false if no parameter is specified while the Boolean function returns undefined if no parameter is specified Example In the following example expressions are converted from numeric to Boolean values trace Boolean 1 output tru...

Page 130: ...es are compared by value var a Boolean Boolean a a is true var b Boolean Boolean 1 b is true trace a b true Variables representing Boolean objects are compared by reference var a Boolean new Boolean a a is true var b Boolean new Boolean 1 b is true trace a b false See also Boolean class ...

Page 131: ...ex and then by using the Array class s push method var myArray Array Array myArray push 12 trace myArray traces 12 myArray 4 7 trace myArray traces 12 undefined undefined undefined 7 Usage 2 The following example creates an array of length 4 but with no elements defined var myArray Array Array 4 trace myArray length traces 4 trace myArray traces undefined undefined undefined undefined Usage 3 The ...

Page 132: ...used in a switch the break statement instructs Flash to skip the rest of the statements in that case block and jump to the first statement following the enclosing switch statement In nested loops the break statement only skips the rest of the immediate loop and does not break out of the entire series of nested loops For breaking out of an entire series of nested loops see try catch finally Example...

Page 133: ...break 133 See also for for in do while while switch case continue throw try catch finally ...

Page 134: ...case statement outside a switch statement it produces an error and the script doesn t compile Note You should always end the statement s parameter with a break statement If you omit the break statement from the statement s parameter it continues executing with the next case statement instead of exiting the switch statement Example The following example defines conditions for the switch statement t...

Page 135: ...case 135 See also break default strict equality switch ...

Page 136: ...use the fully qualified class name of the form base sub1 sub2 MyClass for more information see Using packages on page 57 Also the class s AS file must be stored within the path in a directory structure that reflects the package structure such as base sub1 sub2 MyClass as for more information see Understanding the classpath on page 64 If a class definition is of the form class MyClass it is in the ...

Page 137: ...m_leafType this bloomSeason param_bloomSeason Create methods to return property values because best practice recommends against directly referencing a property of a class function getLeafType String return leafType function getBloomSeason String return bloomSeason In your script use the new operator to create a Plant object var pineTree Plant new Plant Evergreen N A Confirm parameters were passed ...

Page 138: ... jakob_mc MovieClip this createEmptyMovieClip jakob_mc this getNextHighestDepth var jakob ImageLoader new ImageLoader http www macromedia com devnet mx blueprint articles nielsen spotlight_jnielsen jpg jakob_mc _x 10 _y 10 _alpha 70 _rotation 5 See also dynamic extends implements import interface new Object registerClass ...

Page 139: ...ample The following example first sets and then clears an interval call function callback trace interval called getTimer ms var intervalID Number setInterval callback 1000 You need to clear the interval when you have finished using the function Create a button called clearInt_btn and use the following ActionScript to clear setInterval clearInt_btn onRelease function clearInterval intervalID trace ...

Page 140: ... the loop body and jump to the top of the loop where the condition is tested trace example 1 var i Number 0 while i 10 if i 3 0 i continue trace i i In the following do while loop continue causes the Flash interpreter to skip the rest of the loop body and jump to the bottom of the loop where the condition is tested trace example 2 var i Number 0 do if i 3 0 i continue trace i i while i 10 In a for...

Page 141: ...g for in loop continue causes the Flash interpreter to skip the rest of the loop body and jump back to the top of the loop where the next value in the enumeration is processed for i in _root if i version continue trace i See also do while for for in while ...

Page 142: ...o have a default case statement A default case statement does not have to be last in the list If you use a default statement outside a switch statement it produces an error and the script doesn t compile Example In the following example the expression A does not equal the expressions B or D so the statement following the default keyword is run and the trace statement is sent to the log file var da...

Page 143: ...lly used as a statement as shown in the following example delete x The delete operator can fail and return false if the reference parameter does not exist or cannot be deleted Predefined objects and properties and variables declared with var cannot be deleted You cannot use the delete operator to remove movie clips Example Usage 1 The following example creates an object uses it and deletes it afte...

Page 144: ... undefined Usage 4 The following example shows the behavior of delete on object references var ref1 Object new Object ref1 name Jody copy the reference variable into a new variable and delete ref1 ref2 ref1 delete ref1 trace ref1 name ref1 name output undefined trace ref2 name ref2 name output Jody If ref1 had not been copied into ref2 the object would have been deleted when ref1 was deleted becau...

Page 145: ... statements to be executed before the while loop begins many programmers believe that do while loops are easier to read If the condition always evaluates to true the do while loop is infinite If you enter an infinite loop you encounter problems with Flash Player and eventually get a warning message or crash the player Whenever possible you should use a for loop if you know the number of times you ...

Page 146: ...146 Chapter 5 ActionScript Core Language Elements See also break continue while ...

Page 147: ... be type checked for return type and parameter types Subclasses of dynamic classes are also dynamic For more information see Creating dynamic classes on page 56 Example In the following example class Person2 has not yet been marked as dynamic so calling an undeclared function on it generates an error at compile time class Person2 var name String var age Number function Person2 param_name String pa...

Page 148: ...aig i output Error Scene Scene 1 layer Layer 1 frame 1 Line 14 There is no property with the name dance craig dance true Total ActionScript Errors 1 Reported Errors 1 Add the dynamic keyword to the Person2 class so that the first line appears as follows dynamic class Person2 Test the code again and you see the following output craig dance true craig age 32 craig name Craiggers See also class exten...

Page 149: ...o enclose the block of statements to be executed by the else statement are not necessary if only one statement will execute Example In the following example the else condition is used to check whether the age_txt variable is greater than or less than 18 if age_txt text 18 trace welcome user else trace sorry junior userObject minor true userObject accessAllowed false In the following example curly ...

Page 150: ...If the else if condition returns true the Flash interpreter runs the statements that follow the condition inside curly braces If the else if condition is false Flash skips the statements inside the curly braces and runs the statements following the curly braces Use the else if statement to create branching logic in your scripts If there are multiple branches you should consider using a switch stat...

Page 151: ...introduce escape characters and is not equivalent to the modulo operator Example The following code produces the result someuser 40somedomain 2Ecom var email String someuser somedomain com trace escape email In this example the at symbol was replaced with 40 and the dot symbol was replaced with 2E This is useful if you re trying to pass information to a remote server and the data has special chara...

Page 152: ...variable or property is returned If expression is an object or movie clip a reference to the object or movie clip is returned If the element named in expression cannot be found undefined is returned Example The following example uses eval to set properties for dynamically named movie clips This ActionScript sets the _rotation property for three movie clips called square1_mc square2_mc and square3_...

Page 153: ...asses on page 55 Interfaces can also be extended using the extends keyword An interface that extends another interface includes all the original interface s method declarations Example In the following example the Car class extends the Vehicle class so that all its methods properties and functions are inherited If your script instantiates a Car object methods from both the Car class and the Vehicl...

Page 154: ...th anti lock brakes The following example instantiates a Car object calls a method defined in the Vehicle class start then calls the method overridden by the Car class stop and finally calls a method from the Car class activateCarAlarm var myNewCar Car new Car 2 Red true myNewCar start output Vehicle start myNewCar stop output Car stop with anti lock brakes myNewCar activateCarAlarm output Car act...

Page 155: ...thod overridden by the Truck class reverse then calls a method defined in the Vehicle class stop var myTruck Truck new Truck 2 White 18 myTruck reverse output Truck make beeping sound Vehicle reverse myTruck stop output Vehicle stop See also class implements interface super ...

Page 156: ...er it becomes 0 when it converts false to a string it becomes false For more information see Automatic data typing on page 24 Example This example shows how automatic data typing converts false to a number and to a string var bool1 Boolean Boolean false converts it to the number 0 trace 1 bool1 outputs 1 converts it to a string trace String bool1 outputs String false See also true CHAPTER 5 Action...

Page 157: ...atement evaluates the init initialize expression once and then starts a looping sequence The looping sequence begins by evaluating the condition expression If the condition expression evaluates to true statement is executed and the next expression is evaluated The looping sequence then begins again with the evaluation of the condition expression The curly braces used to enclose the block of statem...

Page 158: ...for loop adds the numbers from 1 to 100 var sum Number 0 for var i Number 1 i 100 i sum i trace sum output 5050 The following example shows that curly braces are not necessary if only one statement will execute var sum Number 0 for var i Number 1 i 100 i sum i trace sum output 5050 See also increment decrement for in var while do while ...

Page 159: ...ers The for in statement iterates over properties of objects in the iterated object s prototype chain Properties of the object are enumerated first then properties of its immediate prototype then properties of the prototype s prototype and so on The for in statement does not enumerate the same property name twice If the object child has prototype parent and both contain the property prop the for i...

Page 160: ...x in myArray trace myArray index myArray index output myArray 2 three myArray 1 two myArray 0 one The following example uses the typeof operator with for in to iterate over a particular type of child for var name in this if typeof this name movieclip trace I have a movie clip child named name Note If you have several movie clips the output consists of the instance names of those clips ...

Page 161: ...nction to control a SWF file playing in Flash Player including projectors A projector is a SWF file saved in a format that can run as a stand alone application that is without Flash Player Command Parameters Purpose quit None Closes the projector fullscreen true or false Specifying true sets Flash Player to full screen mode Specifying false returns the player to normal menu view allowscale true or...

Page 162: ...r the name myDocument the JavaScript function called is myDocument_DoFScommand Usage 3 The fscommand function can send messages to Macromedia Director that are interpreted by Lingo Director s scripting language as strings events or executable Lingo code If the message is a string or an event you must write the Lingo code to receive the message from the fscommand function and carry out an action in...

Page 163: ... a function each time you call it so you can reuse a function in different situations Use the return statement in a function s statement s to cause a function to generate or return a value You can use this statement to define a function with the specified functionname parameters and statement s When a script calls a function the statements in the function s definition are executed Forward referenc...

Page 164: ...arameter and returns the Math pow x 2 of the parameter function sqr x Number return Math pow x 2 var y Number sqr 3 trace y output 9 If the function is defined and used in the same script the function definition may appear after using the function var y Number sqr 3 trace y output 9 function sqr x Number return Math pow x 2 ...

Page 165: ...ject addProperty method in ActionScript 1 For more information see Implicit getter setter methods on page 63 Example In the following example you define a Team class The Team class includes get set methods that let you retrieve and set properties within the class class Team var teamName String var teamCode String var teamPlayers Array new Array function Team param_name String param_code String thi...

Page 166: ...166 Chapter 5 ActionScript Core Language Elements San Fran San Francisco When you trace giants name you use the get method to return the value of the property See also Object addProperty set ...

Page 167: ...rns the number of milliseconds that have elapsed since the SWF file started playing Example In the following example the getTimer and setInterval functions are used to create a simple timer this createTextField timer_txt this getNextHighestDepth 0 0 100 22 function updateTimer Void timer_txt text getTimer var intervalID Number setInterval updateTimer 100 CHAPTER 5 ActionScript Core Language Elemen...

Page 168: ... variables omit this parameter The GET method appends the variables to the end of the URL and is used for small numbers of variables The POST method sends the variables in a separate HTTP header and is used for sending long strings of variables Returns Nothing Description Function loads a document from a specific URL into a window or passes variables to another application at a defined URL To test...

Page 169: ... onRelease function getURL http www macromedia com _blank GET The following ActionScript uses POST to send variables in the HTTP header Make sure you test your documents in a browser window because otherwise your variables are sent using GET var firstName String Gus var lastName String Richardson var age Number 92 getURL http www macromedia com _blank POST See also XML send XML sendAndLoad XMLSock...

Page 170: ...sion number of the Flash Player playing the SWF file var flashVersion String getVersion trace flashVersion output WIN 7 0 19 0 trace version output WIN 7 0 19 0 trace System capabilities version output WIN 7 0 19 0 The following string is returned by the getVersion function WIN 7 0 19 0 This returned string indicates that the platform is Microsoft Windows and the version number of Flash Player is ...

Page 171: ...se the fully qualified name of the variable e g _global variableName Failure to do so will create a local variable of the same name that obscures the global variable you are attempting to set Example The following example creates a top level function factorial that is available to every scope in a SWF file _global factorial function n Number if n 1 return 1 else return n factorial n 1 Note factori...

Page 172: ...are not necessary if only one statement will execute Example The following example uses an if statement to evaluate how long it takes a user to click the submit_btn instance in a SWF file If a user clicks the button more than 10 seconds after the SWF file plays the condition evaluates to true and the message inside the curly braces appears in a text field that s created at runtime using createText...

Page 173: ...face02 Description Keyword specifies that a class must define all the methods declared in the interface or interfaces being implemented For more information see Interfaces as data types on page 59 Example See interface See also class extends interface CHAPTER 5 ActionScript Core Language Elements ...

Page 174: ...rs UserClass after importing import macr util users UserClass var myUser UserClass new UserClass If there are several class files in the package working_directory macr utils users that you want to access you can import them all in a single statement as shown in the following example import macr util users You must issue the import statement before you try to access the imported class without fully...

Page 175: ...path the AS file must be in the same directory as the script containing the include statement To specify a relative path for the AS file use a single dot to indicate the current directory two dots to indicate a parent directory and forward slashes to indicate subdirectories See the following example section To specify an absolute path for the AS file use the format supported by your platform Macin...

Page 176: ...cript file The directory is named ALL_includes include ALL_includes init_script as AS file is specified by an absolute path in Windows Note use of forward slashes not backslashes include C Flash_scripts init_script as AS file is specified by an absolute path on Macintosh include Mac HD Flash_scripts init_script as See also import ...

Page 177: ...bility Flash Player 5 Usage Infinity Description Constant specifies the IEEE 754 value representing positive infinity The value of this constant is the same as Number POSITIVE_INFINITY CHAPTER 5 ActionScript Core Language Elements ...

Page 178: ...ts Infinity Availability Flash Player 5 Usage Infinity Description Constant specifies the IEEE 754 value representing negative infinity The value of this constant is the same as Number NEGATIVE_INFINITY CHAPTER 5 ActionScript Core Language Elements ...

Page 179: ...ed class Tests whether object is an instance of class The instanceof operator does not convert primitive types to wrapper objects For example the following code returns true new String Hello instanceof String The following code returns false Hello instanceof String Example In the following example a for loop is used to loop through the SWF file and trace only TextInput component instances The inst...

Page 180: ...permitted The get and set statements are not allowed in interface definitions FFor more information see Creating and using interfaces on page 58 Example The following example shows several ways to define and implement interfaces in top level package as files Ia B C Ib D Ic E filename Ia as interface Ia function k Number method declaration only function n x Number Number without implementation file...

Page 181: ...rn x x function o Void trace o script file mvar new D trace mvar k 15 trace mvar n 7 49 trace mvar o o interface Ic extends Ia function p Void class E implements Ib Ic function k Number return 25 function n x Number Number return x 5 function o Void trace o function p Void trace p See also class extends implements ...

Page 182: ... value Description Function evaluates expression and returns true if it is a finite number or false if it is infinity or negative infinity The presence of infinity or negative infinity indicates a mathematical error condition such as division by 0 Example The following example shows return values for isFinite isFinite 56 returns true isFinite Number POSITIVE_INFINITY returns false CHAPTER 5 Action...

Page 183: ... trace isNaN Tree returns true trace isNaN 56 returns false trace isNaN Number POSITIVE_INFINITY returns false The following example shows how you can use isNAN to check whether a mathematical expression contains an error var dividend Number var divisor Number divisor 1 trace isNaN dividend divisor output true The output is true because the variable dividend is undefined Do not use isNAN to check ...

Page 184: ...nts NaN Availability Flash Player 5 Usage NaN Description Variable a predefined variable with the IEEE 754 value for NaN not a number To determine if a number is NaN use isNaN See also isNaN Number NaN CHAPTER 5 ActionScript Core Language Elements ...

Page 185: ...theses as well as the newly created object which is referenced using the keyword this The constructor function can use this to set the variables of the object Example The following example creates the Book function and then uses the new operator to create the objects book1 and book2 function Book name String price Number this name name this price price var book1 new Book Confederacy of Dunces 19 9...

Page 186: ...lank line in text output generated by your code Use newline to make space for information that is retrieved by a function or statement in your code Example The following example shows how newline writes output from the trace statement on multiple lines var myName String Lisa myAge Number 30 trace myName myAge trace trace myName newline myAge output Lisa30 Lisa 30 CHAPTER 5 ActionScript Core Langua...

Page 187: ... was provided You can use null to represent values that are missing or that do not have a defined data type Example In a numeric context null evaluates to 0 Equality tests can be performed with null In this statement a binary tree node has no left child so the field for its left child could be set to null if tree left null tree left new TreeNode CHAPTER 5 ActionScript Core Language Elements ...

Page 188: ...e function attempts to parse expression as a decimal number with an optional trailing exponent that is 1 57505e 3 If expression is NaN the return value is NaN If expression is undefined the return value is NaN Example In the following example a text field is created on the Stage at runtime this createTextField counter_txt this getNextHighestDepth 0 0 100 22 counter_txt autoSize true counter_txt te...

Page 189: ...mand is equivalent to creating an object using the Object constructor see Constructor for the Object class on page 376 Example In the following example a new empty object is created and then the object is populated with values var company Object new Object company name Macromedia Inc company address 600 Townsend Street company city San Francisco company state CA company postal 94103 for var i in c...

Page 190: ...le the pointer is over the button the mouse button is pressed and then rolls outside the button area dragOver While the pointer is over the button the mouse button has been pressed then rolled outside the button and then rolled back over the button keyPress key The specified keyboard key is pressed For the key portion of the parameter specify a key constant You can use this parameter to intercept ...

Page 191: ... startDrag function executes when the mouse is pressed and the conditional script is executed when the mouse is released and the object is dropped on press startDrag this on release trace X this _x trace Y this _y stopDrag See also onClipEvent ...

Page 192: ...s not a part of the initial number If the string does not begin with a number that can be parsed parseFloat returns NaN White space preceding valid integers is ignored as are trailing nonnumeric characters Example The following examples use the parseFloat function to evaluate various types of numbers trace parseFloat 2 output 2 trace parseFloat 2 5 output 2 5 trace parseFloat 2 5 output 2 5 trace ...

Page 193: ...specifying a radix of 8 are interpreted as octal numbers White space preceding valid integers is ignored as are trailing nonnumeric characters Example The examples in this section use the parseInt function to evaluate various types of numbers The following example returns 3 parseInt 3 5 The following example returns NaN parseInt bar The following example returns 4 parseInt 4foo The following examp...

Page 194: ...er 5 ActionScript Core Language Elements The following examples show octal number parsing and return 511 which is the decimal representation of the octal 777 parseInt 0777 parseInt 777 8 See also NaN parseFloat ...

Page 195: ...The following example demonstrates how you can hide certain properties within a class using the private keyword Create a new AS file called Login as class Login private var loginUserName String private var loginPassword String public function Login param_username String param_password String this loginUserName param_username this loginPassword param_password public function get username String ret...

Page 196: ...nScript Core Language Elements Because loginPassword is a private variable you cannot access it from outside the Login as class file Attempts to access the private variable generate an error message See also public static ...

Page 197: ...hat also contains private or static variables Example The following example shows how you can use public variables in a class file Create a new class file called User as and enter the following code class User public var age Number public var name String Then create a new FLA or AS file in the same directory and enter the following ActionScript import User var jimmy User new User jimmy age 27 jimm...

Page 198: ...immediately to the calling function If the return statement is used alone it returns undefined You can t return multiple values If you try to do so only the last value is returned In the following example c is returned return a b c If you need to return multiple values you might want to use an array or object instead Example The following example uses the return statement inside the body of the su...

Page 199: ...plicit get set methods are syntactic shorthand for the Object addProperty method in ActionScript 1 For more information see Implicit getter setter methods on page 63 Example The following example creates a Login class that demonstrates how the set keyword can be used to set private variables class Login private var loginUserName String private var loginPassword String public function Login param_u...

Page 200: ...ActionScript var gus Login new Login Gus Smith trace gus username output Gus gus username Rupert trace gus username output Rupert In the following example the get function executes when the value is traced The set function triggers only when you pass it a value as shown in the line gus username Rupert See also get Object addProperty ...

Page 201: ...data type associated with the variable in a class file no compiler error is generated A subtle but important distinction to bear in mind is that the parameter variableString is a string not a variable name If you pass an existing variable name as the first parameter to set without enclosing the name in quotation marks the variable is evaluated before the value of expression is assigned to it For e...

Page 202: ... Language Elements The following code loops three times and creates three new variables called caption0 caption1 and caption2 for var i 0 i 3 i set caption i this is caption i trace caption0 trace caption1 trace caption2 See also var ...

Page 203: ...ying integer that you can pass to clearInterval to cancel the interval Description Function calls a function or a method or an object at periodic intervals while a SWF file plays You can use an interval function to update variables from a database or to update a time display Example Usage 1 The following example calls an anonymous function every 1000 milliseconds 1 second setInterval function trac...

Page 204: ...function by using clearInterval when you have finished using it as shown in the following example create an event listener object for our MovieClipLoader instance var listenerObjectbject new Object listenerObject onLoadInit function target_mc MovieClip trace start interval after the target movie clip loaded create a callback which executes about every 1000 ms 1 second and calls the intervalFunc fu...

Page 205: ...val 205 jpeg_mcl addListener listenerObject jpeg_mcl loadClip http www macromedia com software central images klynch_breezo jpg this createEmptyMovieClip jpeg_mc this getNextHighestDepth See also clearInterval ...

Page 206: ...ber using the instance You can use this keyword in class definitions only not in interface definitions Example The following example demonstrates how you can use the static keyword to create a counter that tracks how many instances of the class have been created Because the numInstances variable is static it will be created only once for the entire class not for every single instance Create a new ...

Page 207: ...e or other ActionScript element Example The following example uses quotation marks to indicate that the value of the variable yourGuess is the literal string Prince Edward Island and not the name of a variable The value of province is a variable not a literal to determine the value of province the value of yourGuess must be located var yourGuess String Prince Edward Island submit_btn onRelease fun...

Page 208: ...by calling the string property for the object or by calling Object toString if no such property exists If expression is undefined the return value is undefined If expression is a Boolean value the return string is true or false If expression is a movie clip the return value is the target path of the movie clip in slash notation Note Slash notation is not supported in Flex applications Example In t...

Page 209: ...constructor function to invoke the superclass version of the constructor function and can optionally pass parameters to it This is useful for creating a subclass that performs additional initialization but also invokes the superclass constructor to perform superclass initialization Example In the following example you create two classes You use the super keyword in the Sock class to call functions...

Page 210: ...on trace mySock getColor mySock setColor Orange trace mySock getColor The following result is written to the log file Clothes I am the constructor Socks I am the constructor Socks I am getColor Clothes I am getColor maroon Socks I am setColor Socks I am getColor Clothes I am getColor Orange If you forgot to put the super keyword in the Sock class s getColor method then the getColor method could ca...

Page 211: ...f true All switch statements should include a default case The default case should include a break statement that prevents a fall through error if another case is added later When a case falls through it doesn t have a break statement Example In the following example if the String fromCharCode Key getAscii parameter evaluates to A the trace statement that follows case A executes if the parameter e...

Page 212: ...12 Chapter 5 ActionScript Core Language Elements case i trace you pressed I or i break default trace you pressed some other key Key addListener listenerObj See also strict equality break case default if ...

Page 213: ... str String Defined in ApplyThis as function conctStr x String String return x x function addStr String return str Then in a FLA or AS file add the following ActionScript var obj ApplyThis new ApplyThis var abj ApplyThis new ApplyThis abj str defined in FLA or AS trace obj addStr call abj null output defined in FLA or AS trace obj addStr call this null output undefined trace obj addStr call obj nu...

Page 214: ...n of Simple as Example In the following example the keyword this references the Circle object function Circle radius Number Void this radius radius this area Math PI Math pow radius 2 var myCircle new Circle 4 trace myCircle area In the following statement inside a MovieClip onPress handler the keyword this references the current movie clip this square_mc onPress function startDrag this this squar...

Page 215: ...ot contain an symbol the function throws an error function checkEmail email String if email indexOf 1 throw new Error Invalid email address checkEmail someuser_theirdomain com The following code then calls the checkEmail function within a try code block If the email_txt string does not contain a valid e mail address the error message appears in a text field error_txt try checkEmail Joe Smith catch...

Page 216: ...ipt import InvalidEmailAddress function checkEmail email String if email indexOf 1 throw new InvalidEmailAddress try checkEmail Joe Smith catch e this createTextField error_txt this getNextHighestDepth 0 0 100 22 error_txt autoSize true error_txt text e toString See also Error class try catch finally ...

Page 217: ...ssages in the log file Use the expression parameter to check whether a condition exists or to write values to the log file Example The following example uses a trace statement to write the methods and properties of the dynamically created text field called error_txt to the log file this createTextField error_txt this getNextHighestDepth 0 0 100 22 for var i in error_txt trace error_txt i error_txt...

Page 218: ...rue in an if statement var shouldExecute Boolean code that sets shouldExecute to either true or false goes here shouldExecute is set to true for this example shouldExecute true if shouldExecute true trace your statements here true is also implied so the if statement could also be written if shouldExecute trace your statements here The following example shows how automatic data typing converts true...

Page 219: ...block completes normally then the code in the finally block is still executed The finally block executes even if the try block exits using a return statement A try block must be followed by a catch block a finally block or both A single try block can have multiple catch blocks but only one finally block You can nest try blocks as many levels deep as desired The error parameter specified in a catch...

Page 220: ...or not an error occurs Because setInterval is used clearInterval must be placed in the finally block to ensure that the interval is cleared from memory myFunction function trace this is myFunction try myInterval setInterval this myFunction 1000 throw new Error my error catch myError Error trace error caught myError finally clearInterval myInterval trace error is cleared In the following example th...

Page 221: ...de block throws a different type of object In this case myRecordSet is an instance of a hypothetical class named RecordSet whose sortRows method can throw two types of errors RecordSetException and MalformedRecord In the following example the RecordSetException and MalformedRecord objects are subclasses of the Error class Each is defined in its own AS class file For more information see Chapter 2 ...

Page 222: ...invokes the sortRows method on an instance of the RecordSet class It defines catch blocks for each type of error that is thrown by sortRows import RecordSet var myRecordSet RecordSet new RecordSet try myRecordSet sortRows trace everything is fine catch e RecordSetException trace e toString catch e MalformedRecord trace e toString See also Error class throw class extends ...

Page 223: ...ession is a string movie clip object function number or Boolean value The following table shows the results of the typeof operator on each type of expression nu Example In the following example all instances in a SWF file and their types are traced and written to a log file for i in _root trace _root i typeof _root i Parameter Output String string Movie clip movieclip Button object Text field obje...

Page 224: ...e compared with the strict equality operator they compare as not equal Example In the following example the variable x has not been declared and therefore has the value undefined In the first section of code the equality operator compares the value of x to the value undefined and the appropriate result is sent to the log file In the second section of code the equality operator compares the values ...

Page 225: ...mat converting all hexadecimal sequences to ASCII characters and returns the string Example The following example shows the escape to unescape conversion process var email String user somedomain com trace email var escapedEmail String escape email trace escapedEmail var unescapedEmail String unescape escapedEmail trace unescapedEmail The following result is written to the log file user somedomain ...

Page 226: ... length 25 syntax error When you use var you can strictly type the variable For more information see Strict data typing on page 24 Note You must also use var when declaring properties inside class definitions in external scripts Class files also support public private and static variable scopes See Creating Custom Classes with ActionScript 2 0 on page 45 and see private public and static Example T...

Page 227: ...ned values if someUndefinedVariable void 0 trace someUndefinedVariable is undefined The previous code can also be written in the following way if someUndefinedVariable undefined trace someUndefinedVariable is undefined Usage 2 In the following example a function that returns a value is defined using the Void return type which results in a compile time error function myFunction Void return This wil...

Page 228: ...pression condition is evaluated 2 If condition evaluates to true or a value that converts to the Boolean value true such as a nonzero number go to step 3 Otherwise the while statement is completed and execution resumes at the next statement after the while loop 3 Run the statement block statement s 4 Go to step 1 Looping is commonly used to perform an action while a counter variable is less than a...

Page 229: ...while 229 i 3 The following result is written to the log file 0 3 6 9 12 15 18 See also do while continue for for in ...

Page 230: ...y length and my_array concat In another example if object is state california any actions or statements inside the with statement are called from inside the california instance To find the value of an identifier in the statement s parameter ActionScript starts at the beginning of the scope chain specified by the object and searches for the identifier at each level of the scope chain in a specific ...

Page 231: ...ly In the following example the built in Math object is placed at the front of the scope chain Setting Math as a default object resolves the identifiers cos sin and PI to Math cos Math sin and Math PI respectively The identifiers a x y and r are not methods or properties of the Math object but because they exist in the object activation scope of the function polar they resolve to the corresponding...

Page 232: ...that you can use in a Macromedia Flex application However many of the items described in this chapter are not for use in typical Flex applications and should be used only as necessary For more information on the items that Macromedia recommends that you use in a Flex application see Flex ActionScript and MXML API Reference ...

Page 233: ...e if the Flash Player is communicating with an accessibility aid usually a screen reader false otherwise Description Method indicates whether an accessibility aid is currently active and the player is communicating with it Use this method when you want your application to behave differently in the presence of a screen reader or other accessibility aid Note If you call this method within one or two...

Page 234: ...s all changes to _accProps accessibility properties objects to take effect For information on setting accessibility properties see _accProps If you modify the accessibility properties for multiple objects only one call to Accessibility updateProperties is necessary multiple calls can result in reduced performance and unintelligible screen reader results Example If you change an image and want to u...

Page 235: ...TextArea and TextInput controls For changes to these properties to take effect you must call Accessibility updateProperties To determine whether the player is running in an environment that supports accessibility aids use System capabilities hasAccessibility The following table lists the name and data type of each _accProps property and the kinds of objects to which the property can be applied Pro...

Page 236: ...s name Price Accessibility updateProperties If you are specifying several accessibility properties make as many changes as you can before calling Accessibility updateProperties instead of calling it after each property statement as shown in the following example _accProps name Pet Store animal_mc _accProps name Animal animal_mc _accProps description Cat dog fish etc price_mc _accProps name Price p...

Page 237: ...ge arguments callee Function Description Property refers to the function that is currently being called Example You can use the arguments callee property to make an anonymous function that is recursive as shown in the following example factorial function x Number if x 1 return 1 else return x arguments callee x 1 trace factorial 3 output 6 The following example is a named recursive function functi...

Page 238: ... functions a caller function named function1 which calls a another function named function2 define the caller function named function1 var function1 Function function function2 hello from function1 define the callee function named function2 var function2 Function function aString String if arguments caller function1 trace function2 was called by function1 trace aString call function1 function1 Out...

Page 239: ...eturn arguments length trace getArgLength one two three output 3 trace getArgLength one two output 2 trace getArgLength one two three four output 4 In the following example the function called listSum adds the values passed to it and returns the sum The function uses a for loop to examine each argument passed If the value is a number the value is added to the sum variable At the end of the functio...

Page 240: ...od Description Array concat Concatenates the parameters and returns them as a new array Array join Joins all elements of an array into a string Array pop Removes the last element of an array and returns its value Array push Adds one or more elements to the end of an array and returns the array s new length Array reverse Reverses the direction of an array Array shift Removes the first element from ...

Page 241: ...s of arrays an empty array an array with a specific length but whose elements have undefined values or an array whose elements have specific values Usage 1 If you don t specify any parameters an array with a length of 0 is created Usage 2 If you specify only a length an array is created with length number of elements Each element s value is set to undefined Usage 3 If you use the element parameter...

Page 242: ...Donna go_gos_array 1 Nina trace go_gos_array join returns Belinda Nina Kathy Charlotte Jane Donna See also Array length array access Array concat Availability Flash Player 5 Usage my_array concat value0 Object value1 valueN Array Parameters value0 valueN Numbers elements or strings to be concatenated in a new array If you don t pass any values a duplicate of my_array is created Returns An array De...

Page 243: ... new Array a b c 2 and 3 are elements in a nested array var n_array Array new Array 1 2 3 4 var x_array Array a_array concat n_array trace x_array 0 a trace x_array 1 b trace x_array 2 c trace x_array 3 1 trace x_array 4 2 3 trace x_array 5 4 Array join Availability Flash Player 5 Usage my_array join separator String String Parameters separator A character or string that separates array elements i...

Page 244: ...Array Europa Io Callisto Titan Rhea trace a_nested_array join returns Europa Io Callisto Titan Rhea See Also String split Array length Availability Flash Player 5 Usage my_array length Number Description Property a non negative integer specifying the number of elements in the array This property is automatically updated when new elements are added to the array When you assign a value to an array e...

Page 245: ... pop Object Parameters None Returns The value of the last element in the specified array Description Method removes the last element from an array and returns the value of that element Example The following code creates the myPets_array array containing four elements and then removes its last element var myPets_array Array new Array cat dog bird fish var popped Object myPets_array pop trace popped...

Page 246: ...tement in the last line sends the new length of myPets_array 4 to the log file var myPets_array Array new Array cat dog var pushed Number myPets_array push bird fish trace pushed displays 4 See Also Array pop Array shift Array unshift Array reverse Availability Flash Player 5 Usage my_array reverse Void Parameters None Returns Nothing Description Method reverses the array in place Example The foll...

Page 247: ...ays cat trace myPets_array displays dog bird fish See also Array pop Array push Array unshift Array slice Availability Flash Player 5 Usage my_array slice start Number end Number Array Parameters start A number specifying the index of the starting point for the slice If start is a negative number the starting point begins at the end of the array where 1 is the last element end A number specifying ...

Page 248: ...ments from the array var myPets_array Array new Array cat dog fish canary parrot var myFlyingPets_array Array myPets_array slice 2 trace myFlyingPets_array traces canary parrot The following example creates an array of five pets and uses slice with a negative end parameter to copy the middle element from the array var myPets_array Array new Array cat dog fish canary parrot var myAquaticPets_array ...

Page 249: ...r option Flash returns an array that reflects the results of the sort and does not modify the array Otherwise Flash returns nothing and modifies the array to reflect the sort order Description Method sorts the elements in an array Flash sorts according to Unicode values ASCII is a subset of Unicode By default Array sort works as described in the following list Sorting is case sensitive Z precedes ...

Page 250: ...herries apples Usage 2 The following example uses Array sort with a compare function var passwords_array Array new Array mom glam ana ring jay mag anne home regina silly function order a b Number Entries to be sorted are in form name password Sort using only the name part of the entry as a key var name1 String a split 0 var name2 String b split 0 if name1 name2 return 1 else if name1 name2 return ...

Page 251: ...ut each option see Description on page 251 Returns The return value depends on whether you pass any parameters as described in the following list If you specify a value of 4 or Array UNIQUESORT for option and two or more elements being sorted have identical sort fields Flash returns a value of 0 and does not modify the array If you specify a value of 8 or Array RETURNINDEXEDARRAY for option Flash ...

Page 252: ...rray sort To pass multiple flags in numeric format separate them with the bitwise OR operator or add the values of the flags together The following code shows three ways to specify a numeric descending sort my_array sortOn someFieldName 2 16 my_array sortOn someFieldName 18 my_array sortOn someFieldName Array DESCENDING Array NUMERIC Consider the following array var my_array Array new Array my_arr...

Page 253: ...ge 4 After any sort that doesn t pass a value of 8 for option my_array sortOn age Array NUMERIC my_array 0 age 3 my_array 1 age 4 my_array 2 age 29 my_array 3 age 35 Performing a sort that returns an index array doesn t change the elements in the array as shown in the following example Before sorting my_array 0 age 29 my_array 1 age 3 my_array 2 age 35 my_array 3 age 4 After a sort that returns an...

Page 254: ... rec_array length i trace rec_array i name rec_array i city results john omaha john kansas city bob omaha rec_array sortOn name city for i 0 i rec_array length i trace rec_array i name rec_array i city results bob omaha john kansas city john omaha rec_array sortOn city name for i 0 i rec_array length i trace rec_array i name rec_array i city results john kansas city bob omaha john omaha See also b...

Page 255: ... original array var myPets_array Array new Array cat dog bird fish trace myPets_array splice 1 dog bird fish trace myPets_array cat The following example creates an array and splices it using element index 1 for the start parameter and the number 2 for the deleteCount parameter This removes two elements from the array starting with the second element leaving the first and last elements in the orig...

Page 256: ...he following example creates my_array converts it to a string and writes 1 2 3 4 5 to the log file my_array Array new Array my_array 0 1 my_array 1 2 my_array 2 3 my_array 3 4 my_array 4 5 trace my_array toString displays 1 2 3 4 5 See Also Array join String split Array unshift Availability Flash Player 5 Usage my_array unshift value1 Object value2 valueN Number Parameters value1 valueN One or mor...

Page 257: ...The following example shows the use of Array unshift var pets_array Array new Array dog cat fish trace pets_array dog cat fish pets_array unshift ferrets gophers engineers trace pets_array ferrets gophers engineers dog cat fish ...

Page 258: ...xpression This parameter is optional Returns A reference to a Boolean object Description Constructor creates a Boolean object If you omit the x parameter the Boolean object is initialized with a value of false If you specify a value for the x parameter the method evaluates it and returns the result as a Boolean value according to the rules in the Boolean function Example The following code creates...

Page 259: ...value of the Boolean myBool is myBool toString myBool false trace The value of the Boolean myBool is myBool toString Boolean valueOf Availability Flash Player 5 Usage myBoolean valueOf Boolean Parameters None Returns A Boolean value Description Method returns true if the primitive value type of the specified Boolean object is true false otherwise Example The following example shows how this method...

Page 260: ...ocal time Date getHours Returns the hour according to local time Date getMilliseconds Returns the milliseconds according to local time Date getMinutes Returns the minutes according to local time Date getMonth Returns the month according to local time Date getSeconds Returns the seconds according to local time Date getTime Returns the number of milliseconds since midnight January 1 1970 universal t...

Page 261: ...te Sets the date according to universal time Returns the new time in milliseconds Date setUTCFullYear Sets the year according to universal time Returns the new time in milliseconds Date setUTCHours Sets the hour according to universal time Returns the new time in milliseconds Date setUTCMilliseconds Sets the milliseconds according to universal time Returns the new time in milliseconds Date setUTCM...

Page 262: ...s optional millisecond An integer from 0 to 999 This parameter is optional Returns A reference to a Date object Description Constructor constructs a new Date object that holds the specified date or the current date and time Example The following example retrieves the current date and time var now_date Date new Date The following example creates a new Date object for Mary s birthday August 12 1974 ...

Page 263: ...the returned values of Date getMonth Date getDate and Date getFullYear var today_date Date new Date var date_str String today_date getDate today_date getMonth 1 today_date getFullYear trace date_str displays current date in United States date format Date getDay Availability Flash Player 5 Usage my_date getDay Number Parameters None Returns An integer representing the day of the week Description Me...

Page 264: ...Year Number Parameters None Returns An integer representing the year Description Method returns the full year a four digit number such as 2000 of the specified Date object according to local time Local time is determined by the operating system on which Flash Player is running Example The following example uses the constructor to create a Date object and send the value returned by the getFullYear ...

Page 265: ...ate getHours var my_date Date new Date var hourObj Object getHoursAmPm my_date getHours trace hourObj hours trace hourObj ampm function getHoursAmPm hour24 Number Object var returnObj Object new Object returnObj ampm hour24 12 AM PM var hour12 Number hour24 12 if hour12 0 hour12 12 returnObj hours hour12 return returnObj Date getMilliseconds Availability Flash Player 5 Usage my_date getMillisecond...

Page 266: ...ameters None Returns An integer Description Method returns the minutes an integer from 0 to 59 of the specified Date object according to local time Local time is determined by the operating system on which Flash Player is running Example The following example uses the constructor to create a Date object based on the current time and uses the getMinutes method to return the minutes value from that ...

Page 267: ...ame of the month var my_date Date new Date trace my_date getMonth trace getMonthAsString my_date getMonth function getMonthAsString month Number String var monthNames_array Array new Array January February March April May June July August September October November December return monthNames_array month Date getSeconds Availability Flash Player 5 Usage my_date getSeconds Number Parameters None Ret...

Page 268: ... in time when comparing two or more Date objects Example The following example uses the constructor to create a Date object based on the current time and uses the getTime method to return the number of milliseconds since midnight January 1 1970 var my_date Date new Date trace my_date getTime Date getTimezoneOffset Availability Flash Player 5 Usage my_date getTimezoneOffset Number Parameters None R...

Page 269: ...n locale and time of year Date getUTCDate Availability Flash Player 5 Usage my_date getUTCDate Number Parameters None Returns An integer Description Method returns the day of the month an integer from 1 to 31 in the specified Date object according to universal time Example The following example creates a new Date object and uses Date getUTCDate and Date getDate The value returned by Date getUTCDat...

Page 270: ...ay_date getUTCDay output will equal getDay plus or minus one Date getUTCFullYear Availability Flash Player 5 Usage my_date getUTCFullYear Number Parameters None Returns An integer Description Method returns the four digit year of the specified Date object according to universal time Example The following example creates a new Date object and uses Date getUTCFullYear and Date getFullYear The value ...

Page 271: ... returned by Date getUTCHours may differ from the value returned by Date getHours depending on the relationship between your local time zone and universal time var today_date Date new Date trace today_date getHours display based on local timezone trace today_date getUTCHours display equals getHours plus or minus 12 Date getUTCMilliseconds Availability Flash Player 5 Usage my_date getUTCMillisecond...

Page 272: ... Usage my_date getUTCMinutes Number Parameters None Returns An integer Description Method returns the minutes an integer from 0 to 59 of the specified Date object according to universal time Example The following example creates a new Date object and uses getUTCMinutes to return the minutes value from the Date object var today_date Date new Date trace today_date getUTCMinutes Date getUTCMonth Avai...

Page 273: ... today_date Date new Date trace today_date getMonth output based on local timezone trace today_date getUTCMonth output equals getMonth plus or minus 1 Date getUTCSeconds Availability Flash Player 5 Usage my_date getUTCSeconds Number Parameters None Returns An integer Description Method returns the seconds an integer from 0 to 59 of the specified Date object according to universal time Example The ...

Page 274: ... getYear output 104 trace today_date getFullYear output 2004 See also Date getFullYear Date setDate Availability Flash Player 5 Usage my_date setDate date Number Parameters date An integer from 1 to 31 Returns An integer Description Method sets the day of the month for the specified Date object according to local time and returns the new time in milliseconds Local time is determined by the operati...

Page 275: ... parameters are specified they are set to local time Local time is determined by the operating system on which Flash Player is running Calling this method does not modify the other fields of the specified Date object but Date getUTCDay and Date getDay can report a new value if the day of the week changes as a result of calling this method Example The following example initially creates a new Date ...

Page 276: ...liseconds Availability Flash Player 5 Usage my_date setMilliseconds millisecond Number Number Parameters millisecond An integer from 0 to 999 Returns An integer Description Method sets the milliseconds for the specified Date object according to local time and returns the new time in milliseconds Local time is determined by the operating system on which Flash Player is running Example The following...

Page 277: ...me and date to 8 00 a m on May 15 2004 and then uses Date setMinutes to change the time to 8 30 a m var my_date Date new Date 2004 4 15 8 0 trace my_date getMinutes output 0 my_date setMinutes 30 trace my_date getMinutes output 30 Date setMonth Availability Flash Player 5 Usage my_date setMonth month Number date Number Number Parameters month An integer from 0 January to 11 December date An intege...

Page 278: ... sets the seconds for the specified Date object in local time and returns the new time in milliseconds Local time is determined by the operating system on which Flash Player is running Example The following example initially creates a new Date object setting the time and date to 8 00 00 a m on May 15 2004 and uses Date setSeconds to change the time to 8 00 45 a m var my_date Date new Date 2004 4 1...

Page 279: ...y_date getDate output 15 trace my_date getHours output 8 trace my_date getMinutes output 30 Date setUTCDate Availability Flash Player 5 Usage my_date setUTCDate date Number Number Parameters date A number an integer from 1 to 31 Returns An integer Description Method sets the date for the specified Date object in universal time and returns the new time in milliseconds Calling this method does not m...

Page 280: ...epresented by the specified Date object Calling this method does not modify the other fields of the specified Date object but Date getUTCDay and Date getDay can report a new value if the day of the week changes as a result of calling this method Example The following example initially creates a new Date object with today s date uses Date setUTCFullYear to change the year value to 2001 and changes ...

Page 281: ...Date object with today s date uses Date setUTCHours to change the time to 8 30 a m and changes the time again to 5 30 47 p m var my_date Date new Date my_date setUTCHours 8 30 trace my_date getUTCHours output 8 trace my_date getUTCMinutes output 30 my_date setUTCHours 17 30 47 trace my_date getUTCHours output 17 trace my_date getUTCMinutes output 30 trace my_date getUTCSeconds output 47 Date setUT...

Page 282: ...d Number Number Parameters minute An integer from 0 to 59 second An integer from 0 to 59 This parameter is optional millisecond An integer from 0 to 999 This parameter is optional Returns An integer Description Method sets the minute for the specified Date object in universal time and returns the new time in milliseconds Example The following example initially creates a new Date object setting the...

Page 283: ...2004 and uses Date setMonth to change the date to June 15 2004 var today_date Date new Date 2004 4 15 trace today_date getUTCMonth output 4 today_date setUTCMonth 5 trace today_date getUTCMonth output 5 Date setUTCSeconds Availability Flash Player 5 Usage my_date setUTCSeconds second Number millisecond Number Number Parameters second An integer from 0 to 59 millisecond An integer from 0 to 999 Thi...

Page 284: ...and returns the new time in milliseconds Local time is determined by the operating system on which Flash Player is running Example The following example creates a new Date object with the date set to May 25 2004 uses setYear to change the year to 1999 and changes the year to 2003 var my_date Date new Date 2004 4 25 trace my_date getYear output 104 trace my_date getFullYear output 2004 my_date setY...

Page 285: ... Number minute Number second Number millisecond Number Number Parameters year A four digit integer that represents the year for example 2000 month An integer from 0 January to 11 December date An integer from 1 to 31 This parameter is optional hour An integer from 0 midnight to 23 11 p m minute An integer from 0 to 59 This parameter is optional second An integer from 0 to 59 This parameter is opti...

Page 286: ...ime This is the universal time variation of the example used for the new Date constructor method var maryBirthday_date Date new Date Date UTC 1974 7 12 trace maryBirthday_date output will be in local time and will vary accordingly for Pacific Daylight Time the output will be seven hours earlier than UTC Sun Aug 11 17 00 00 GMT 0700 1974 ...

Page 287: ...arameters message A string associated with the Error object this parameter is optional Returns A reference to an Error object Description Constructor creates a new Error object If message is specified its value is assigned to the object s Error message property Example In the following example a function throws an error with a specified message if the two strings that are passed to it are not iden...

Page 288: ... a function throws a specified message depending on the parameters entered into theNum If two numbers can be divided SUCCESS and the number are shown Specific errors are shown if you try to divide by 0 or enter only 1 parameter function divideNum num1 Number num2 Number Number if isNaN num1 isNaN num2 throw new Error divideNum function requires two numeric parameters else if num2 0 throw new Error...

Page 289: ...parameters else if denominator 0 throw new DivideByZeroError return numerator denominator try var theNum Number divideNumber 1 0 trace SUCCESS theNum output DivideByZeroError Unable to divide by zero catch e_err DivideByZeroError divide by zero error occurred trace e_err name e_err toString catch e_err Error generic error occurred trace e_err name e_err toString To add a custom error add the follo...

Page 290: ...owing example a function throws an error with a specified message if the two strings that are passed to it are not identical function compareStrings str1_str String str2_str String Void if str1_str str2_str throw new Error Strings to not match try compareStrings Dog dog output Strings to not match catch e_err Error trace e_err toString See also Error message throw try catch finally ...

Page 291: ...sed within any function that ActionScript calls This method also specifies the parameters to be passed to any called function Because apply is a method of the Function class it is also a method of every Function object in ActionScript The parameters are specified as an Array object unlike Function call which specifies parameters as a comma delimited list This is often useful when the number of par...

Page 292: ...e shows how apply passes an array of parameters and specifies the value of this define a function function theFunction trace this myObj this myObj trace arguments arguments instantiate an object var myObj Object new Object create arrays to pass as a parameter to apply var firstArray Array new Array 1 2 3 var secondArray Array new Array a b c use apply to set the value of this to be myObj and send ...

Page 293: ...r of the function invocation needs to be explicitly controlled Normally if a function is invoked as a method of an object within the body of the function this is set to myObject as shown in the following example myObject myMethod 1 2 3 In some situations you might want this to point somewhere else for example if a function must be invoked as a method of an object but is not actually stored as a me...

Page 294: ...ter 6 ActionScript Core Classes var obj Object new myObject myMethod call obj obj The trace statement displays The trace statement sends the following code to the log file this obj true See also Function apply ...

Page 295: ...Key getCode Returns the virtual key code of the last key pressed Key isDown Returns true if the key specified in the parameter is pressed Key isToggled Returns true if the Num Lock or Caps Lock key is activated Key removeListener Removes an object that was previously registered with Key addListener Property Description Key code Key BACKSPACE The key code value for the Backspace key 8 Key CAPSLOCK ...

Page 296: ...istered no change occurs Example The following example creates a new listener object and defines a function for onKeyDown and onKeyUp The last line uses addListener to register the listener with the Key object so that it can receive notification from the key down and key up events var myListener Object new Object myListener onKeyDown function trace You pressed a key Key PGUP The key code value for...

Page 297: ...ener onKeyDown myOnKeyDown Key addListener myListener my_btn onPress myOnPress my_btn _accProps shortcut Ctrl 7 Accessibility updateProperties See also Key getCode Key isDown Key onKeyDown Key onKeyUp Key removeListener Key BACKSPACE Availability Flash Player 5 Usage Key BACKSPACE Number Description Property constant associated with the key code value for the Backspace key 8 Example The following ...

Page 298: ...ssed the Caps Lock key trace tCaps Lock Key isToggled Key CAPSLOCK Key addListener keyListener Information is written to the log file when you press the Caps Lock key The log file writes either true or false depending on whether the Caps Lock is activated using the isToggled method Key CONTROL Availability Flash Player 5 Usage Key CONTROL Number Description Property constant associated with the ke...

Page 299: ...ng example lets you draw lines with the mouse pointer using the Drawing API and listener objects Press the Backspace or Delete key to remove the lines that you draw this createEmptyMovieClip canvas_mc this getNextHighestDepth var mouseListener Object new Object mouseListener onMouseDown function this drawing true canvas_mc moveTo _xmouse _ymouse canvas_mc lineStyle 3 0x99CC00 100 mouseListener onM...

Page 300: ...u press the Spacebar Give a sound in the library a linkage identifier of horn_id for this example var DISTANCE Number 10 var horn_sound Sound new Sound horn_sound attachSound horn_id var keyListener_obj Object new Object keyListener_obj onKeyDown function switch Key getCode case Key SPACE horn_sound start break case Key LEFT car_mc _x DISTANCE break case Key UP car_mc _y DISTANCE break case Key RI...

Page 301: ...ess the arrow keys The car_mc instance stops when you press Enter and delete the onEnterFrame event var DISTANCE Number 5 var keyListener Object new Object keyListener onKeyDown function switch Key getCode case Key LEFT car_mc onEnterFrame function this _x DISTANCE break case Key UP car_mc onEnterFrame function this _y DISTANCE break case Key RIGHT car_mc onEnterFrame function this _x DISTANCE bre...

Page 302: ...t the current timer convert the value to seconds and round it to two decimal places var timer Number Math round getTimer 10 100 trace you pressed the Esc key getTimer ms timer s Key addListener keyListener Key getAscii Availability Flash Player 5 Usage Key getAscii Number Parameters None Returns A number an integer that represents the ASCII value of the last key pressed Description Method returns ...

Page 303: ...xample adds a call to Key getAscii to show how the two methods differ The main difference is that Key getAscii differentiates between uppercase and lowercase letters and Key getCode does not var keyListener Object new Object keyListener onKeyDown function trace For the last key typed trace tThe Key code is Key getCode trace tThe ASCII value is Key getAscii trace Key addListener keyListener Key get...

Page 304: ...Listener keyListener The following example adds a call to Key getAscii to show how the two methods differ The main difference is that Key getAscii differentiates between uppercase and lowercase letters and Key getCode does not var keyListener Object new Object keyListener onKeyDown function trace For the last key typed trace tThe Key code is Key getCode trace tThe ASCII value is Key getAscii trace...

Page 305: ... Property constant associated with the key code value for the Insert key 45 Example The following example creates a new listener object and defines a function for onKeyDown The last line uses addListener to register the listener with the Key object so that it can receive notification from the key down event and write information to the log file var keyListener Object new Object keyListener onKeyDo...

Page 306: ...toggled to an active state false otherwise Although the term toggled usually means that something is switched between two options the method Key isToggled will only return true if the key is toggled to an active state On the Macintosh the key code values for the Caps Lock and Num Lock keys are identical Example The following example calls the isToggled method any time a key is pressed and executes...

Page 307: ...ject new Object keyListener onKeyDown function capsLock_txt htmlText b Caps Lock b Key isToggled Key CAPSLOCK numLock_txt htmlText b Num Lock b Key isToggled 144 Key addListener keyListener Key LEFT Availability Flash Player 5 Usage Key LEFT Number Description Property constant associated with the key code value for the Left Arrow key 37 Example The following example moves a movie clip called car_...

Page 308: ...and use addListener to register the listener with the Key object as shown in the following example var keyListener Object new Object keyListener onKeyDown function trace DOWN Code Key getCode tACSII Key getAscii tKey chr Key getAscii keyListener onKeyUp function trace UP Code Key getCode tACSII Key getAscii tKey chr Key getAscii Key addListener keyListener Listeners enable different pieces of code...

Page 309: ...ey getAscii tKey chr Key getAscii Key addListener keyListener Listeners enable different pieces of code to cooperate because multiple listeners can receive notification about a single event See also Key addListener Key PGDN Availability Flash Player 5 Usage Key PGDN Number Description Property constant associated with the key code value for the Page Down key 34 Example The following example rotate...

Page 310: ...eyListener Key removeListener Availability Flash Player 6 Usage Key removeListener listener Object Boolean Parameters listener An object Returns If the listener was successfully removed the method returns true If the listener was not successfully removed for example because the listener was not on the Key object s listener list the method returns false Description Method removes an object previous...

Page 311: ...ed car_mc a constant distance 10 when you press the arrow keys A sound plays when you press the Spacebar Give a sound in the library a linkage identifier of horn_id for this example var DISTANCE Number 10 var horn_sound Sound new Sound horn_sound attachSound horn_id var keyListener_obj Object new Object keyListener_obj onKeyDown function switch Key getCode case Key SPACE horn_sound start break cas...

Page 312: ...yscale 2 Key addListener keyListener Key SPACE Availability Flash Player 5 Usage Key SPACE Number Description Property constant associated with the key code value for the Spacebar 32 Example The following example moves a movie clip called car_mc a constant distance 10 when you press the arrow keys A sound plays when you press the Spacebar Give a sound in the library a linkage identifier of horn_id...

Page 313: ... associated with the key code value for the Tab key 9 Example The following example creates a text field and displays the date in the text field when you press Tab this createTextField date_txt this getNextHighestDepth 0 0 100 22 date_txt autoSize true var keyListener Object new Object keyListener onKeyDown function if Key isDown Key TAB var today_date Date new Date date_txt text today_date toStri...

Page 314: ...ebar Give a sound in the library a linkage identifier of horn_id for this example var DISTANCE Number 10 var horn_sound Sound new Sound horn_sound attachSound horn_id var keyListener_obj Object new Object keyListener_obj onKeyDown function switch Key getCode case Key SPACE horn_sound start break case Key LEFT car_mc _x DISTANCE break case Key UP car_mc _y DISTANCE break case Key RIGHT car_mc _x DI...

Page 315: ...tree stored in the XML object The LoadVars class follows the same security restrictions as the XML class For information about using the LoadVars class and example code see Using the LoadVars class on page 69 Method summary for the LoadVars class Method Description LoadVars addRequestHeader Adds or changes HTTP headers for POST operations LoadVars decode Converts a variable string to properties of...

Page 316: ...oadVars new LoadVars LoadVars addRequestHeader Availability Flash Player 6 Usage my_lv addRequestHeader headerName String headerValue String Void my_lv addRequestHeader headerName_1 String headerValue_1 headerName_n headerValue_n String Void Property Description LoadVars contentType A string that indicates the MIME type of the data LoadVars loaded A Boolean value that indicates whether a load or s...

Page 317: ...Range ETag Host Last Modified Locations Max Forwards Proxy Authenticate Proxy Authorization Public Range Retry After Server TE Trailer Transfer Encoding Upgrade URI Vary Via Warning and WWW Authenticate Example The following example adds a custom HTTP header named SOAPAction with a value of Foo to the my_lv object my_lv addRequestHeader SOAPAction Foo The following example creates an array named h...

Page 318: ...end LoadVars sendAndLoad LoadVars decode Availability Flash Player 7 Usage my_lv decode variables String Void Parameters variables A URL encoded query string containing name value pairs Returns Nothing Description Method converts the variable string to properties of the specified LoadVars object This method is used internally by the LoadVars onData event handler Most users do not need to call this...

Page 319: ...uccessfully and how much data loads into the SWF file You must replace the URL parameter of the LoadVars load command so that the parameter refers to a valid text file using HTTP If you attempt to use this example to load a local file that resides on your hard disk this example will not work properly because in test movie mode Flash Player loads local files in their entirety To see this code work ...

Page 320: ...did not transmit an HTTP content length Example The following example uses a ProgressBar instance and a LoadVars object to download a text file When you test the file two things write to the log file whether the file loads successfully and how much data loads into the SWF file You must replace the URL parameter of the LoadVars load command so that the parameter refers to a valid text file using HT...

Page 321: ...tion Method downloads variables from the specified URL parses the variable data and places the resulting variables into my_lv Any properties in my_lv with the same names as downloaded variables are overwritten Any properties in my_lv with different names than downloaded variables are not deleted This is an asynchronous action The downloaded data must be in the MIME content type application x www f...

Page 322: ...ion Property a Boolean value that indicates whether a load or sendAndLoad operation has completed undefined by default When a LoadVars load or LoadVars sendAndLoad operation is started the loaded property is set to false when the operation completes the loaded property is set to true If the operation has not completed or has failed with an error the loaded property remains set to false This proper...

Page 323: ...can be either undefined or a string that contains the URL encoded name value pairs downloaded from the server If the src parameter is undefined an error occurred while downloading the data from the server The default implementation of LoadVars onData invokes LoadVars onLoad You can override this default implementation by assigning a custom function to LoadVars onData but LoadVars onLoad is not cal...

Page 324: ...is invoked This handler is undefined by default This event handler is similar to XML onLoad LoadVars loaded LoadVars load LoadVars sendAndLoad LoadVars send Availability Flash Player 6 Usage my_lv send url String target String method String Boolean Parameters url A string the URL to which to upload variables target A string the browser window or frame in which any response will appear You can ente...

Page 325: ...the parent or top level frame use _parent or _top as the target parameter appear in a named frame use the frame s name as a string for the target parameter A successful send method call will always open a new browser window or replace content in an existing window or frame If you would rather send information to a server and continue playing your SWF file without opening a new window or replacing ...

Page 326: ...in the same manner as LoadVars send Variables are downloaded into targetObject in the same manner as LoadVars load The value you pass for url must be in exactly the same domain For example a SWF file at www someDomain com can load data only from sources that are also at www someDomain com If you want to load data from a different domain you can place a cross domain policy file on the server hostin...

Page 327: ...e instantiates a new LoadVars object creates two properties and uses toString to return a string containing both properties in URL encoded format var my_lv LoadVars new LoadVars my_lv name Gary my_lv age 26 trace my_lv toString output age 26 name Gary ...

Page 328: ...nd LocalConnection connect commands specify the same connection name lc_name Code in the receiving SWF file this createTextField result_txt 1 10 10 100 22 result_txt border true var receiving_lc LocalConnection new LocalConnection receiving_lc methodToExecute function param1 Number param2 Number result_txt text param1 param2 receiving_lc connect lc_name Code in the sending SWF file var sending_lc ...

Page 329: ...ving_lc methodToExecute function param1 Number param2 Number result_txt text param1 param2 LocalConnection domain Returns a string representing the superdomain of the location of the current SWF file LocalConnection send Invokes a method on a specified LocalConnection object Event handler Description LocalConnection allowDomain Invoked whenever the current receiving LocalConnection object receives...

Page 330: ...method from a sending LocalConnection object Flash expects the code you implement in this handler to return a Boolean value of true or false If the handler doesn t return true the request from the sending object is ignored and the method is not invoked When this event handler is absent Flash Player applies a default security policy which is equivalent to the following code my_lc allowDomain functi...

Page 331: ...ion of this method For example if you load a SWF file into my_mc you can then implement this method by checking whether the domain argument matches the domain of my_mc _url You must parse the domain out of the full URL contained in my_mc _url If you do this make sure that you wait until the SWF file in my_mc is loaded because the _url property will not have its final correct value until the file i...

Page 332: ...tatus_ta text LocalConnection connected successfully break case error status_ta text LocalConnection encountered an error break sending_lc send _mylc sayHello name_ti text send_button addEventListener click sendListener In the following example the receiving SWF file which resides in thisDomain com accepts commands only from SWF files located in thisDomain com or thatDomain com var aLocalConn Loca...

Page 333: ...y other SWF files hosted using the HTTPS protocol This implementation maintains the integrity provided by the HTTPS protocol Using this method to override the default behavior is not recommended as it compromises HTTPS security However you might need to do so for example if you need to permit access to HTTPS files published for Flash Player 7 or later from HTTP files published for Flash Player 6 A...

Page 334: ...t to accept commands for example when you want to issue a LocalConnection connect command using the same connectionName parameter in another SWF file Example The following example closes a connection called receiving_lc when you click a Button component instance called close_button this createTextField welcome_txt this getNextHighestDepth 10 10 100 22 this createTextField status_txt this getNextHi...

Page 335: ...efore calling this method as shown in all the examples in this section By default Flash Player resolves connectionName into a value of superdomain connectionName where superdomain is the superdomain of the SWF file containing the LocalConnection connect command For example if the SWF file containing the receiving LocalConnection object is located at www someDomain com connectionName resolves to so...

Page 336: ...m any domain will be accepted the SWF with the receiving LocalConnection object can be moved to another domain without altering any sending LocalConnection objects For more information see the discussion of connectionName in LocalConnection send and also the LocalConnection allowDomain and LocalConnection domain entries Note Colons are used as special characters to separate the superdomain from th...

Page 337: ... to SWF 1 and passes two variables The first variable contains the MP3 file to stream and the second variable is the filename that you display in the Label component instance in SWF 1 play_btn onRelease function var sending_lc LocalConnection new LocalConnection sending_lc send lc_name playMP3 song1 mp3 Album 01 Song SWF 3 contains a button called play_btn When you click the button it connects to ...

Page 338: ...objects that are located in the same domain you probably don t need to use this command Example In the following example a receiving SWF file accepts commands only from SWF files located in the same domain or at macromedia com If both the sending and receiving SWF files are Flash Player 6 then use the superdomain var my_lc LocalConnection new LocalConnection my_lc allowDomain function sendingDomai...

Page 339: ...m result replyMethod aResult n1 123 and n2 456 It then executes the following line of code this send mydomain com result aResult 123 456 The aResult method line 54 shows the value returned by aSum 579 The receiving SWF at http www mydomain com folder movie swf contains the following code 1 var aLocalConnection LocalConnection new LocalConnection 2 aLocalConnection allowDomain function 3 Allow conn...

Page 340: ...ption Event handler invoked after a sending LocalConnection object tries to send a command to a receiving LocalConnection object If you want to respond to this event handler you must create a function to process the information object sent by the LocalConnection object If the information object returned by this event handler contains a level value of status Flash successfully sent the command to a...

Page 341: ...whether the SWF file connects to another local connection object called lc_name A TextInput component called name_ti a TextArea instance called status_ta and a Button instance called send_button are used to display content var sending_lc LocalConnection var sendListener Object new Object sendListener click function evt Object sending_lc new LocalConnection sending_lc onStatus function infoObject O...

Page 342: ...efault If you are implementing communication between different domains you need to define connectionName in both the sending and receiving LocalConnection objects in such a way that Flash does not add the current superdomain to connectionName You can do this in one of the following two ways Use an underscore _ at the beginning of connectionName in both the sending and receiving LocalConnection obj...

Page 343: ...LocalConnection send 343 See also LocalConnection allowDomain LocalConnection connect LocalConnection domain LocalConnection onStatus ...

Page 344: ...lculate radian values before calling the method and then provide the calculated value as the parameter or you can provide the entire right side of the equation with the angle s measure in degrees in place of degrees as the radian parameter To calculate a radian value use the following formula radians degrees Math PI 180 The following is an example of passing the equation as a parameter to calculat...

Page 345: ...e y Math random Returns a pseudo random number between 0 0 and 1 0 Math round Rounds to the nearest integer Math sin Computes a sine Math sqrt Computes a square root Math tan Computes a tangent Property Description Math E Euler s constant and the base of natural logarithms approximately 2 718 Math LN2 The natural logarithm of 2 approximately 0 693 Math LOG2E The base 2 logarithm of e approximately...

Page 346: ...age Math acos x Number Number Parameters x A number from 1 0 to 1 0 Returns A number the arc cosine of the parameter x Description Method computes and returns the arc cosine of the number specified in the parameter x in radians Example The following example displays the arc cosine for several values trace Math acos 1 output 3 14159265358979 trace Math acos 0 output 1 5707963267949 trace Math acos ...

Page 347: ...ethods and properties of the Math class are emulated using approximations and might not be as accurate as the non emulated math functions that Flash Player 5 supports Usage Math atan tangent Number Number Parameters tangent A number that represents the tangent of an angle Returns A number between negative pi divided by 2 and positive pi divided by 2 Description Method computes and returns the valu...

Page 348: ...e point y x in radians when measured counterclockwise from a circle s x axis where 0 0 represents the center of the circle The return value is between positive pi and negative pi Example The following example displays the following radians from the specified coordinates 10 0 trace Math atan2 10 0 output 1 5707963267949 See also Math acos Math asin Math atan Math cos Math sin Math tan Math ceil Ava...

Page 349: ... measured in radians Returns A number from 1 0 to 1 0 Description Method computes and returns the cosine of the specified angle in radians To calculate a radian see Description on page 344 of the Math class entry Example The following example displays the cosine for several different angles trace Math cos 0 0 degree angle Output 1 trace Math cos Math PI 2 90 degree angle Output 6 12303176911189e 1...

Page 350: ... a one year period var principal Number 100 var simpleInterest Number 100 var continuouslyCompoundedInterest Number 100 Math E principal trace Beginning principal principal trace Simple interest after one year simpleInterest trace Continuously compounded interest after one year continuouslyCompoundedInterest Output Beginning principal 100 Simple interest after one year 100 Continuously compounded ...

Page 351: ...s that Flash Player 5 supports Usage Math floor x Number Number Parameters x A number or expression Returns The integer that is both closest to and less than or equal to parameter x Description Method returns the floor of the number or expression specified in the parameter x The floor is the closest integer that is less than or equal to the specified number or expression Example The following code...

Page 352: ...e as accurate as the non emulated math functions that Flash Player 5 supports Usage Math LN2 Number Description Constant a mathematical constant for the natural logarithm of 2 expressed as loge2 with an approximate value of 0 6931471805599453 Math LN10 Availability Flash Player 5 In Flash Player 4 the methods and properties of the Math class are emulated using approximations and might not be as ac...

Page 353: ...value of 1 442695040888963387 Example This example traces the value of Math LOG2E trace Math LOG2E Output 1 44269504088896 Math LOG10E Availability Flash Player 5 In Flash Player 4 the methods and properties of the Math class are emulated using approximations and might not be as accurate as the non emulated math functions that Flash Player 5 supports Usage Math LOG10E Number Description Constant a...

Page 354: ...alue Example The following example displays Thu Dec 30 00 00 00 GMT 0700 2004 which is the larger of the evaluated expressions var date1 Date new Date 2004 11 25 var date2 Date new Date 2004 11 30 var maxDate Number Math max date1 getTime date2 getTime trace new Date maxDate toString See Also Math min Math min Availability Flash Player 5 In Flash Player 4 the methods and properties of the Math cla...

Page 355: ... supports Usage Math PI Number Parameters None Returns Nothing Description Constant a mathematical constant for the ratio of the circumference of a circle to its diameter expressed as pi with a value of 3 141592653589793 Example The following example draws a circle using the mathematical constant pi and the Drawing API drawCircle this 100 100 50 function drawCircle mc MovieClip x Number y Number r...

Page 356: ... y Example The following example uses Math pow and Math sqrt to calculate the length of a line this createEmptyMovieClip canvas_mc this getNextHighestDepth var mouseListener Object new Object mouseListener onMouseDown function this origX _xmouse this origY _ymouse mouseListener onMouseUp function this newX _xmouse this newY _ymouse var minY Math min this origY this newY var nextDepth Number canvas...

Page 357: ...andom number because it is not generated by a truly random natural phenomenon such as radioactive decay Example The following example returns a random number between two specified integers function randRange min Number max Number Number var randomNum Number Math round Math random max min min return randomNum for var i 0 i 25 i trace randRange 4 11 Math round Availability Flash Player 5 In Flash Pl...

Page 358: ...or Math sin Availability Flash Player 5 In Flash Player 4 the methods and properties of the Math class are emulated using approximations and might not be as accurate as the non emulated math functions that Flash Player 5 supports Usage Math sin x Number Number Parameters x A number that represents an angle measured in radians Returns A number the sine of the specified angle between 1 0 and 1 0 Des...

Page 359: ...r 4 the methods and properties of the Math class are emulated using approximations and might not be as accurate as the non emulated math functions that Flash Player 5 supports Usage Math sqrt x Number Number Parameters x A number or expression greater than or equal to 0 Returns A number if parameter x is greater than or equal to zero NaN not a number otherwise Description Method computes and retur...

Page 360: ...Math class are emulated using approximations and might not be as accurate as the non emulated math functions that Flash Player 5 supports Usage Math SQRT1_2 Number Description Constant a mathematical constant for the square root of one half with an approximate value of 0 7071067811865476 Example This example traces the value of Math SQRT1_2 trace Math SQRT1_2 Output 0 707106781186548 Math SQRT2 Av...

Page 361: ...raws a circle using the mathematical constant pi the tangent of an angle and the Drawing API drawCircle this 100 100 50 function drawCircle mc MovieClip x Number y Number r Number Void mc lineStyle 2 0xFF0000 100 mc moveTo x r y mc curveTo r x Math tan Math PI 8 r y Math sin Math PI 4 r x Math sin Math PI 4 r y mc curveTo Math tan Math PI 8 r x r y x r y mc curveTo Math tan Math PI 8 r x r y Math ...

Page 362: ...tener newListener Object Parameters newListener An object Returns Nothing Method Description Mouse addListener Registers an object to receive onMouseDown onMouseMove onMouseWheel and onMouseUp notification Mouse hide Hides the mouse pointer in the SWF file Mouse removeListener Removes an object that was registered with addListener Mouse show Displays the mouse pointer in the SWF file Method Descri...

Page 363: ...od invoked Multiple objects can listen for mouse notifications If the listener newListener is already registered no change occurs See also Mouse onMouseDown Mouse onMouseMove Mouse onMouseUp Mouse onMouseWheel Mouse hide Availability Flash Player 5 Usage Mouse hide Number Parameters None Returns An integer either 0 or 1 If the mouse pointer was hidden before the call to Mouse hide then the return ...

Page 364: ...ectangle whenever the user clicks drags and releases the mouse at runtime this createEmptyMovieClip canvas_mc this getNextHighestDepth var mouseListener Object new Object mouseListener onMouseDown function this isDrawing true this orig_x _xmouse this orig_y _ymouse this target_mc canvas_mc createEmptyMovieClip canvas_mc getNextHighestDepth mouseListener onMouseMove function if this isDrawing this ...

Page 365: ...fferent pieces of code to cooperate because multiple listeners can receive notification about a single event Example The following example uses the mouse pointer as a tool to draw lines using onMouseMove and the Drawing API The user draws a line when they drag the mouse pointer this createEmptyMovieClip canvas_mc this getNextHighestDepth var mouseListener Object new Object mouseListener onMouseDow...

Page 366: ...ooperate because multiple listeners can receive notification about a single event Example The following example uses the mouse pointer as a tool to draw lines using onMouseMove and the Drawing API The user draws a line when they drag the mouse pointer The user stops drawing the line when they release the mouse button this createEmptyMovieClip canvas_mc this getNextHighestDepth var mouseListener Ob...

Page 367: ...o use the onMouseWheel listener you must create a listener object You can then define a function for onMouseWheel and use addListener to register the listener with the Mouse object Note Mouse wheel event listeners are available only in Windows versions of Flash Player Example The following example shows how to create a listener object that responds to mouse wheel events In this example the x coord...

Page 368: ...e and lets the user draw lines in the SWF file at runtime using the mouse pointer One button clears all of the lines from the SWF file The second button removes the mouse listener so the user cannot draw lines The third button adds the mouse listener after it is removed so the user can draw lines again Add the following ActionScript Add an instance of the Button component to be placed in the Libra...

Page 369: ...ner click function evt Object Mouse removeListener mouseListener evt target enabled false startDrawing_button enabled true stopDrawing_button addEventListener click stopDrawingListener var startDrawingListener Object new Object startDrawingListener click function evt Object Mouse addListener mouseListener evt target enabled false stopDrawing_button enabled true startDrawing_button addEventListener...

Page 370: ... my_mc Give a movie clip a Linkage identifier of cursor_help_id and add the following ActionScript my_mc onRollOver function Mouse hide this attachMovie cursor_help_id cursor_mc this getNextHighestDepth _x this _xmouse _y this _ymouse my_mc onMouseMove function this cursor_mc _x this _xmouse this cursor_mc _y this _ymouse my_mc onRollOut function Mouse show this cursor_mc removeMovieClip See also ...

Page 371: ...ew Number 1234 myNumber toString The following example assigns the value of the MIN_VALUE property to a variable declared without the use of the constructor var smallest Number Number MIN_VALUE Method summary for the Number class Property summary for the Number class The properties in the following table are constants Method Description Number toString Returns the string representation of a Number...

Page 372: ...g the properties of a Number object The new Number constructor is primarily used as a placeholder A Number object is not the same as the Number function that converts a parameter to a primitive value Example The following code constructs new Number objects var n1 Number new Number 3 4 var n2 Number new Number 10 See also Number Number MAX_VALUE Availability Flash Player 5 Usage Number MAX_VALUE Nu...

Page 373: ... Example The following ActionScript writes the largest and smallest representable numbers to the log file trace Number MIN_VALUE Number MIN_VALUE trace Number MAX_VALUE Number MAX_VALUE This code logs the following values Number MIN_VALUE 4 94065645841247e 324 Number MAX_VALUE 1 79769313486232e 308 Number NaN Availability Flash Player 5 Usage Number NaN Description Property the IEEE 754 value repr...

Page 374: ...ult negResult output negResult Infinity Number POSITIVE_INFINITY Availability Flash Player 5 Usage Number POSITIVE_INFINITY Description Property specifies the IEEE 754 value representing positive infinity The value of this property is the same as that of the constant Infinity Positive infinity is a special numeric value that is returned when a mathematical operation or function returns a value lar...

Page 375: ...r 9 trace myNumber toString 2 output 1001 trace myNumber toString 8 output 11 The following example results in a hexadecimal value var r Number new Number 250 var g Number new Number 128 var b Number new Number 114 var rgb String 0x r toString 16 g toString 16 b toString 16 trace rgb output rgb 0xFA8072 Hexadecimal equivalent of the color salmon Number valueOf Availability Flash Player 5 Usage myN...

Page 376: ...s This parameter is optional Method Description Object addProperty Creates a getter setter property on an object Object registerClass Associates a movie clip symbol with an ActionScript object class Object toString Converts the specified object to a string and returns it Object unwatch Removes the watchpoint that Object watch created Object valueOf Returns the primitive value of an object Object w...

Page 377: ...n object If you pass the value null for this parameter the property is read only Returns A Boolean value true if the property is successfully created false otherwise Description Method creates a getter setter property When Flash reads a getter setter property it invokes the get function and the function s return value becomes the value of prop When Flash writes a getter setter property it invokes ...

Page 378: ...nal method getTitle returns a read only value that is associated with the property bookname When a script retrieves the value of myBook bookcount the ActionScript interpreter automatically invokes myBook getQuantity When a script modifies the value of myBook bookcount the interpreter invokes myObject setQuantity The bookname property does not specify a set function so attempts to modify bookname a...

Page 379: ...ng return Catcher in the Rye Book prototype addProperty bookcount Book prototype getQuantity Book prototype setQuantity Book prototype addProperty bookname Book prototype getTitle null var myBook new Book myBook bookcount 5 trace You ordered myBook bookcount copies of myBook bookname The following example shows how to use the implicit getter and setter functions available in ActionScript 2 0 For m...

Page 380: ...owever in the following example the Object constructor property converts primitive data types such as the string literal seen here into wrapper objects The instanceof operator does not perform any conversion as seen in the following example var my_str String sven trace my_str constructor String output true trace my_str instanceof String output false See Also instanceof Object __proto__ Availabilit...

Page 381: ...l is already registered to a class this method replaces it with the new registration Object __resolve Availability Flash Player 6 Usage myObject __resolve function name String your statements here Parameters name A string representing the name of the undefined property Returns Nothing Description Property a reference to a user defined function that is invoked if ActionScript code refers to an unde...

Page 382: ...unctions Using __resolve redirects undefined method calls to a generic function named myFunction instantiate a new object var myObject Object new Object define a function for __resolve to call myObject myFunction function name trace Method name was called define the __resolve function myObject __resolve function name return function this myFunction name test __resolve using undefined method names ...

Page 383: ...lved in the same way as other undefined properties Added code is in bold typeface instantiate a new object var myObject Object new Object define a function for __resolve to call myObject myFunction function name trace Method name was called define the __resolve function myObject __resolve function name reserve the name onStatus for local use if name onStatus return undefined trace Resolve called f...

Page 384: ... this myFunction apply this arguments create a new object method and assign it the reference this name f return the reference to the function return f test __resolve using undefined method names with parameters myObject someMethod hello output Method someMethod was called with arguments hello myObject someOtherMethod hello world output Method someOtherMethod was called with arguments hello world O...

Page 385: ... works var myNumber Number 5 trace typeof myNumber output number trace myNumber toString output 5 trace typeof myNumber toString output string The following example shows how to override toString in a custom class First create a text file named Vehicle as that contains only the Vehicle class definition and place it into your Classes folder inside your Configuration folder contents of Vehicle as cl...

Page 386: ...alse otherwise Description Method removes a watchpoint that Object watch created This method returns a value of true if the watchpoint is successfully removed false otherwise Example See the example for Object watch See also Object addProperty Object watch Object valueOf Availability Flash Player 5 Usage myObject valueOf Object Parameters None Returns The primitive value of the specified object or...

Page 387: ... new Array object containing two simple elements In this case both toString and valueOf return the same value one two var myArray Array new Array one two trace myArray toString output one two trace myArray valueOf output one two See the example for Object toString for an example of the return value of Object valueOf for a custom class that overrides toString Object watch Availability Flash Player ...

Page 388: ...h method Only a single watchpoint can be registered on a property Subsequent calls to Object watch on the same property replace the original watchpoint The Object watch method behaves similarly to the Object watch function in JavaScript 1 2 and later The primary difference is the userData parameter which is a Flash addition to Object watch that Netscape Navigator does not support You can pass the ...

Page 389: ...event handler passing as parameters the name of the property to watch speed a reference to the callback function speedWatcher the speedLimit of 55 as the userData parameter myObject watch speed speedWatcher 55 set the speed property to 54 then to 57 myObject speed 54 output You are not speeding myObject speed 57 output You are speeding unwatch the object myObject unwatch speed myObject speed 54 th...

Page 390: ... you can configure your document to dynamically format Flash content that is appropriate for the printer settings These user layout properties are read only and cannot be changed by Flash Player Method summary for the PrintJob class You must use the methods for PrintJob class in the order listed in the following table Constructor for the PrintJob class Availability Flash Player 7 Usage my_pj new P...

Page 391: ...ls to addPage was successful You should always check for successful calls to start and addPage before calling send if pagesToPrint 0 my_pj send print page s clean up delete my_pj delete object You cannot create a second PrintJob object while the first one is still active You cannot create a second PrintJob object by calling new PrintJob while the first PrintJob object is still active the second Pr...

Page 392: ...s the conversion rate depends on the screen and its resolution If the screen is set to display 72 pixels per inch for example one point is equal to one pixel If you omit the printArea parameter or if it is passed incorrectly the full Flex screen area of target is printed If you don t want to specify a value for printArea but want to specify a value for options or frameNumber pass null for printAre...

Page 393: ...ven t passed a value for printArea and the Flex screen is larger than the printable area the same type of clipping takes place If you want to scale a movie clip before you print it set its MovieClip _xscale and MovieClip _yscale properties before calling this method and set them back to their original values afterward The scale of a movie clip has no relation to printArea That is if you specify th...

Page 394: ...n area 400 pixels wide and 400 pixels high of frame 3 of the dance_mc movie clip in bitmap format if my_pj addPage dance_mc xMin 0 xMax 400 yMin 0 yMax 400 printAsBitmap true 3 pageCount Starting at 0 0 print an area 400 pixels wide and 600 pixels high of frame 3 of the dance_mc movie clip in vector format at 50 of its actual size var x Number dance_mc _xscale var y Number dance_mc _yscale dance_m...

Page 395: ...age failed you should check that calls to PrintJob addpage and PrintJob start were successful before calling PrintJob send var my_pj PrintJob new PrintJob if my_pj start if my_pj addPage this my_pj send delete my_pj Example See PrintJob addPage and PrintJob start See also PrintJob addPage PrintJob start PrintJob start Availability Flash Player 7 Usage my_pj start Boolean Parameters None Returns A ...

Page 396: ...ialog box any subsequent calls to PrintJob addPage and PrintJob send will fail However if you test for this return value and don t send PrintJob addPage commands as a result you should still delete the PrintJob object to make sure the print spooler is cleared as shown in the following example var my_pj PrintJob new PrintJob var myResult Boolean my_pj start if myResult addPage and send statements h...

Page 397: ... an 8 5 x 11 portrait page pageAdded my_pj addPage this xMin 0 xMax 600 yMin 0 yMax 800 else my_pj orientation is landscape Now the printArea measurements are appropriate for an 11 x 8 5 landscape page pageAdded my_pj addPage this xMin 0 xMax 750 yMin 0 yMax 600 send pages from the spooler to the printer if pageAdded my_pj send clean up delete my_pj See also PrintJob addPage PrintJob send ...

Page 398: ...ed objects as large as 100K When you try to save a larger object Flash Player shows the Local Storage dialog box which lets the user allow or deny local storage for the domain that is requesting access Ensure that your Flex screen size is at least 215 x 138 pixels this is the minimum size Flash requires to display the dialog box If the user clicks Allow the object is saved and SharedObject onStatu...

Page 399: ...r the SharedObject class Property summary for the SharedObject class Event handler summary for the SharedObject class Constructor for the SharedObject class For information on creating local shared objects see SharedObject getLocal SharedObject clear Availability Flash Player 7 Usage my_so clear Void Method Description SharedObject clear Purges all the data from the shared object and deletes the s...

Page 400: ...y_so clear trace after my_so clear for var prop in my_so data trace t prop This ActionScript writes the following message to the log file before my_so clear name after my_so clear SharedObject data Availability Flash Player 6 Usage myLocalSharedObject data Object Description Property the collection of attributes assigned to the data property of the object these attributes can be shared and or stor...

Page 401: ...te To create private values for a shared object values that are available only to the client instance while the object is in use and are not stored with the object when it is closed create properties that are not named data to store them as shown in the following example var my_so SharedObject SharedObject getLocal superfoo my_so favoriteColor blue my_so favoriteNightClub The Bluenote Tavern my_so...

Page 402: ...to a file when the shared object session ends that is when the SWF file is closed when the shared object is garbage collected because it no longer has any references to it or when you call SharedObject clear If this method returns pending the Flash Player shows a dialog box asking the user to increase the amount of disk space available to objects from this domain To allow space for the shared obje...

Page 403: ... Player 6 Usage SharedObject getLocal objectName String localPath String SharedObject Note The correct syntax is SharedObject getLocal To assign the object to a variable use syntax like myLocal_so SharedObject getLocal Parameters objectName A string that represents the name of the object The name can include forward slashes for example work addresses is a legal name Spaces are not allowed in a sha...

Page 404: ...ter move the original SWF file to another location then not even that SWF file will be able to access the data already stored in the shared object You can reduce the likelihood that you will inadvertently restrict access to a shared object by using the localpath parameter The most permissive option is to set the localPath parameter to which makes the shared object available to all SWF files in the...

Page 405: ...ared object by stepping through each of its data properties the more data properties the object has the longer it takes to estimate its size For this reason estimating object size can have significant processing time Therefore you might want to avoid using this method unless you have a specific need for it Example The following example gets the size of the shared object my_so var items_array Array...

Page 406: ...called System onStatus If onStatus is invoked for a particular object and no function is assigned to respond to it Flash processes a function assigned to System onStatus if it exists The following events notify you when certain SharedObject activities occur Example The following example displays different messages based on whether the user chooses to allow or deny the SharedObject object instance ...

Page 407: ...rentUserName my_so onStatus function infoObject Object status_txt htmlText textformat tabStops 50 for var i in infoObject status_txt htmlText b i b t infoObject i status_txt htmlText textformat var flushResult my_so flush 1000001 switch flushResult case pending message_str flush is pending waiting on user interaction break case true message_str flush was successful Requested storage space approved...

Page 408: ...g length property with a string literal Do not confuse a string literal with a String object In the following example the first line of code creates the string literal first_string and the second line of code creates the String object second_string var first_string String foo var second_string String new String foo Use string literals unless you specifically need to use a String object Method summ...

Page 409: ...ng class unless you have a good reason to use a String object rather than a string literal See also String string delimiter String charAt Availability Flash Player 5 Usage my_str charAt index Number String String substring Returns the characters between two indexes in a string String toLowerCase Converts the string to lowercase and returns the result does not change the contents of the original ob...

Page 410: ...ethod is called on the first letter of the string Chris var my_str String Chris var firstChar_str String my_str charAt 0 trace firstChar_str output C See also String charCodeAt String charCodeAt Availability Flash Player 5 Usage my_str charCodeAt index Number Number Parameters index A number an integer that specifies the position of a character in the string The first character is indicated by 0 a...

Page 411: ...nated Returns A string Description Method combines the value of the String object with the parameters and returns the newly formed string the original value my_str is unchanged Example The following example creates two strings and combines them using String concat var stringA String Hello var stringB String World var combinedAB String stringA concat stringB trace combinedAB output Hello World Stri...

Page 412: ...str to search for the substring Returns A number the position of the first occurrence of the specified substring or 1 Description Method searches the string and returns the position of the first occurrence of substring found at or after startIndex within the calling string This index is zero based meaning that the first character in a string is considered to be at index 0 not index 1 If substring ...

Page 413: ...Description Method searches the string from right to left and returns the index of the last occurrence of substring found before startIndex within the calling string This index is zero based meaning that the first character in a string is considered to be at index 0 not index 1 If substring is not found the method returns 1 Example The following example shows how to use lastIndexOf to return the i...

Page 414: ...x is x length 1 Example The following example creates a new String object and uses String length to count the number of characters var my_str String Hello world trace my_str length output 12 The following example loops from 0 to my_str length The code checks the characters within a string and if the string contains the character true writes to the log file If it does not contain the character then...

Page 415: ...If the end parameter is not specified the end of the substring is the end of the string If the character indexed by start is the same as or to the right of the character indexed by end the method returns an empty string Example The following example creates a variable my_str assigns it a String value and then calls the slice method using a variety of values for both the start and end parameters Ea...

Page 416: ...gs of my_str Description Method splits a String object into substrings by breaking it wherever the specified delimiter parameter occurs and returns the substrings in an array If you use an empty string as a delimiter each character in the string is placed as an element in the array If the delimiter parameter is undefined the entire string is placed into the first element of the returned array Exam...

Page 417: ...gth A number the number of characters in the substring being created If length is not specified the substring includes all the characters from the start to the end of the string Returns A string a substring of the specified string Description Method returns the characters in a string from the index specified in the start parameter through the number of characters specified in the length parameter ...

Page 418: ...value 0 is used Returns String a substring of the specified string Description Method returns a string comprising the characters between the points specified by the start and end parameters If the end parameter is not specified the end of the substring is the end of the string If the value of start equals the value of end the method returns an empty string If the value of start is greater than the...

Page 419: ... of that string using toLowerCase to convert all uppercase characters to lowercase characters var upperCase String LOREM IPSUM DOLOR var lowerCase String upperCase toLowerCase trace upperCase upperCase output upperCase LOREM IPSUM DOLOR trace lowerCase lowerCase output lowerCase lorem ipsum dolor See Also String toUpperCase String toUpperCase Availability Flash Player 5 Usage my_str toUpperCase St...

Page 420: ...ase characters and then creates a copy of that string using toUpperCase var lowerCase String lorem ipsum dolor var upperCase String lowerCase toUpperCase trace lowerCase lowerCase output lowerCase lorem ipsum dolor trace upperCase upperCase output upperCase LOREM IPSUM DOLOR See also String toLowerCase ...

Page 421: ...hen accessing local settings such as camera or microphone access permissions or locally persistent data shared objects The default value is true for files published for Flash Player 7 or later and false for files published for Flash Player 6 Method Description System setClipboard Replaces the contents of the system Clipboard with a text string System showSettings Displays a Flash Player Settings p...

Page 422: ...re you want to store settings and data If you want to change this property from its default value do so near the beginning of your script The property can t be changed after any activity that requires access to local settings such as System showSettings or SharedObject getLocal If you use MovieClip loadMovie or MovieClipLoader loadClip to load one SWF file into another all of the files share a sin...

Page 423: ... when a class specific onStatus function does not exist Create generic function System onStatus function genericError Object Your script would do something more meaningful here trace An error has occurred Please try again The following example shows how to create an onStatus function for an instance of the NetStream class Create function for NetStream object videoStream_ns onStatus function infoOb...

Page 424: ...nto the out_txt field this createTextField in_txt this getNextHighestDepth 10 10 160 120 in_txt multiline true in_txt border true in_txt text lorum ipsum this createTextField out_txt this getNextHighestDepth 10 140 160 120 out_txt multiline true out_txt border true out_txt type input copy_btn onRelease function System setClipboard in_txt text Selection setFocus out_txt System showSettings Availabi...

Page 425: ...Camera get Microphone get SharedObject getLocal System useCodepage Availability Flash Player 6 Usage System useCodepage Boolean Description Property a Boolean value that tells Flash Player whether to use Unicode or the traditional code page of the operating system running the player to interpret external text files The default value of System useCodepage is false When the property is set to false ...

Page 426: ... operating system If you set System useCodepage to true remember that the traditional code page of the operating system running the player must include the characters used in your external text file in order for the text to display For example if you load an external text file that contains Chinese characters those characters cannot display on a system that uses the CP1252 code page because that c...

Page 427: ...DEB t V WIN 207 2C0 2 C19 2C0 M Macromedia 20Windows R 1600x1200 DP 72 COL color AR 1 0 OS Window s 20XP L en PT External AVD f LFD f WD f Property summary for the System capabilities object All properties of the System capabilities object are read only Property Description Server string System capabilities avHardwareDisable Specifies whether the user s camera and microphone are enabled or disable...

Page 428: ...nning L System capabilities localFileReadDisable Specifies whether the player will attempt to read anything including the first SWF file the player launches with from the user s hard disk LFD System capabilities manufacturer Indicates the manufacturer of Flash Player M System capabilities os Indicates the operating system hosting Flash Player OS System capabilities pixelAspectRatio Indicates the p...

Page 429: ...also Camera get Microphone get System showSettings System capabilities hasAccessibility Availability Flash Player 6 Usage System capabilities hasAccessibility Boolean Description Read only property a Boolean value that is true if the player is running in an environment that supports communication between Flash Player and accessibility aids false otherwise The server string is ACC Example The follo...

Page 430: ...oolean value that is true if the player can encode an audio stream such as that coming from a microphone false otherwise The server string is AE Example The following example traces the value of this read only property trace System capabilities hasAudioEncoder System capabilities hasEmbeddedVideo Availability Flash Player 6 r65 Usage System capabilities hasEmbeddedVideo Boolean Description Read on...

Page 431: ...6 r65 Usage System capabilities hasPrinting Boolean Description Read only property a Boolean value that is true if the player is running on a system that supports printing false otherwise The server string is PR Example The following example traces the value of this read only property trace System capabilities hasPrinting System capabilities hasScreenBroadcast Availability Flash Player 6 r79 Usage...

Page 432: ...erver false otherwise The server string is SP Example The following example traces the value of this read only property trace System capabilities hasScreenPlayback System capabilities hasStreamingAudio Availability Flash Player 6 r65 Usage System capabilities hasStreamingAudio Boolean Description Read only property a Boolean value that is true if the player can play streaming audio false otherwise...

Page 433: ...value that is true if the player can encode a video stream such as that coming from a web camera false otherwise The server string is VE Example The following example traces the value of this read only property trace System capabilities hasVideoEncoder System capabilities isDebugger Availability Flash Player 6 Usage System capabilities isDebugger Boolean Description Read only property a Boolean va...

Page 434: ...lish systems no longer includes the country code In Flash Player 6 all English systems return the language code and the two letter country code subtag en US In Flash Player 7 English systems return only the language code en Second on Microsoft Windows systems this property now returns the User Interface UI Language In Flash Player 6 on the Microsoft Windows platform System capabilities language re...

Page 435: ...at Flash Player launches with from the user s hard disk For example attempts to read a file on the user s hard disk using XML load or LoadVars load will fail if this property is set to true Reading runtime shared libraries will also be blocked if this property is set to true but reading local shared objects is allowed without regard to the value of this property The server string is LFD Example Th...

Page 436: ... current operating system The os property can return the following strings Windows XP Windows 2000 Windows NT Windows 98 ME Windows 95 Windows CE available only in Flash Player SDK not in the desktop version Linux and MacOS The server string is OS Example The following example traces the value of this read only property trace System capabilities os System capabilities pixelAspectRatio Availability...

Page 437: ...rnet Explorer The server string is PT Example The following example traces the value of this read only property trace System capabilities playerType System capabilities screenColor Availability Flash Player 6 Usage System capabilities screenColor String Description Read only property a string that indicates the screen color This property can have the value color gray or bw which represents color g...

Page 438: ...s the maximum horizontal resolution of the screen The server string is R which returns both the width and height of the screen Example The following example traces the value of this read only property trace System capabilities screenResolutionX System capabilities screenResolutionY Availability Flash Player 6 Usage System capabilities screenResolutionY Number Description Read only property an inte...

Page 439: ... Macromedia 20Windows R 1600x1200 DP 72 COL color AR 1 0 OS Windows 20 XP L en PT External AVD f LFD f WD f Example The following example traces the value of this read only property trace System capabilities serverString System capabilities version Availability Flash Player 6 Usage System capabilities version String Description Read only property a string containing the Flash Player platform and v...

Page 440: ...ntified domains access objects and variables in the calling SWF file or in any other SWF file from the same domain as the calling SWF file In files playing in Flash Player 7 or later the parameter s passed must follow exact domain naming rules For example to allow access by SWF files hosted at either www domain com or store domain com both domain names must be passed For Flash Player 6 System secu...

Page 441: ...value until the file is completely loaded The best way to determine when a child SWF finishes loading is to use MovieClipLoader onLoadComplete The opposite situation can also occur that is you might create a child SWF file that wants to allow its parent to script it but doesn t know what the domain of its parent will be In this situation call System security allowDomain _parent _url from the child...

Page 442: ...ch access in SWF files published for Flash Player 7 or later Note It is sometimes necessary to call System security allowInsecureDomain with an argument that exactly matches the domain of the SWF file in which this call appears This is different from System security allowDomain which is never necessary to call with a SWF file s own domain as an argument The reason this is sometimes necessary with ...

Page 443: ...o com sub dir deep vars2 txt allowed loadVariables http foo com elsewhere vars3 txt not allowed You can load any number of policy files using loadPolicyFile When considering a request that requires a policy file Flash Player always waits for the completion of any policy file downloads before denying a request As a final fallback if no policy file specified with loadPolicyFile authorizes a request ...

Page 444: ...licy allow access from domain to ports 507 allow access from domain foo com to ports 507 516 allow access from domain bar com to ports 516 523 allow access from domain www foo com to ports 507 516 523 allow access from domain www bar com to ports cross domain policy A policy file obtained from the old default location crossdomain xml on an HTTP server on port 80 implicitly authorizes access to all...

Page 445: ... XML class Method Description XML addRequestHeader Adds or changes HTTP headers for POST operations XML appendChild Appends a node to the end of the specified object s child list XML cloneNode Clones the specified node and optionally recursively clones all children XML createElement Creates a new XML element XML createTextNode Creates a new XML text node XML getBytesLoaded Returns the number of by...

Page 446: ... XML nodeType The type of the specified node XML element or text node XML nodeValue The text of the specified node if the node is a text node XML parentNode Read only references the parent node of the specified node XML previousSibling Read only references the previous sibling in the parent node s child list XML status A numeric status code that indicates the success or failure of an XML document ...

Page 447: ... new empty XML object var my_xml XML new XML The following example creates an XML object by parsing the XML text specified in the source parameter and populates the newly created XML object with the resulting XML document tree var other_xml XML new XML state name California city San Francisco city state See also XML createElement XML createTextNode XML addRequestHeader Availability Flash Player 6 ...

Page 448: ...oxy Authenticate Proxy Authorization Public Range Retry After Server TE Trailer Transfer Encoding Upgrade URI Vary Via Warning and WWW Authenticate Example The following example adds a custom HTTP header named SOAPAction with a value of Foo to an XML object named my_xml my_xml addRequestHeader SOAPAction Foo The following example creates an array named headers that contains two alternating HTTP he...

Page 449: ...pendChild method to the XML document named doc1 Shows how to move a node using the appendChild method by moving the root node from doc1 to doc2 Clones the root node from doc2 and appends it to doc1 Creates a new node and appends it to the root node of the XML document doc1 var doc1 XML new XML var doc2 XML new XML create a root node and add it to doc1 var rootnode XMLNode doc1 createElement root d...

Page 450: ... that attribute s value by using the color as the key index as the following code shows var myColor String doc firstChild attributes color Example The following example writes the names of the XML attributes to the log file create a tag called mytag with an attribute called name with value Val var doc XML new XML mytag name Val item mytag assign the value of the name attribute to variable y var y ...

Page 451: ...reateElement rootNode create three child nodes var oldest XMLNode doc createElement oldest var middle XMLNode doc createElement middle var youngest XMLNode doc createElement youngest add the rootNode as the root of the XML document tree doc appendChild rootNode add each of the child nodes as children of rootNode rootNode appendChild oldest rootNode appendChild middle rootNode appendChild youngest ...

Page 452: ...d lastChild are also null Example The following example shows how to use the XML cloneNode method to create a copy of a node create a new XML document var doc XML new XML create a root node var rootNode XMLNode doc createElement rootNode create three child nodes var oldest XMLNode doc createElement oldest var middle XMLNode doc createElement middle var youngest XMLNode doc createElement youngest a...

Page 453: ... XML send or XML sendAndLoad method The default is application x www form urlencoded which is the standard MIME content type used for most HTML forms Example The following example creates a new XML document and checks its default content type create a new XML document var doc XML new XML trace the default content type trace doc contentType output application x www form urlencoded The following exa...

Page 454: ...createTextNode method are the constructor methods for creating nodes for an XML object Example The following example creates three XML nodes using the createElement method create an XML document var doc XML new XML create three XML nodes using createElement var element1 XMLNode doc createElement element1 var element2 XMLNode doc createElement element2 var element3 XMLNode doc createElement element...

Page 455: ...isting XML nodes create an XML document var doc XML new XML create three XML nodes using createElement var element1 XMLNode doc createElement element1 var element2 XMLNode doc createElement element2 var element3 XMLNode doc createElement element3 place the new nodes into the XML tree doc appendChild element1 element1 appendChild element2 element1 appendChild element3 create two XML text nodes usin...

Page 456: ...ion the XML docTypeDecl property is set to undefined The XML toString method outputs the contents of XML docTypeDecl immediately after the XML declaration stored in XML xmlDecl and before any other text in the XML object If XML docTypeDecl is undefined no DOCTYPE declaration is output Example The following example uses the XML docTypeDecl property to set the DOCTYPE declaration for an XML object m...

Page 457: ...rootNode as the root of the XML document tree doc appendChild rootNode add each of the child nodes as children of rootNode rootNode appendChild oldest rootNode appendChild middle rootNode appendChild youngest use firstChild to iterate through the child nodes of rootNode for var aNode XMLNode rootNode firstChild aNode null aNode aNode nextSibling trace aNode output oldest middle youngest See also X...

Page 458: ...his example will not work properly because in test movie mode Flash Player loads local files in their entirety create a new XML document var doc XML new XML var checkProgress function xmlObj XML var bytesLoaded Number xmlObj getBytesLoaded var bytesTotal Number xmlObj getBytesTotal var percentLoaded Number Math floor bytesLoaded bytesTotal 100 trace milliseconds elapsed getTimer trace bytesLoaded ...

Page 459: ...le creates a new XML packet If the root node has child nodes the code loops over each child node to display the name and value of the node Add the following ActionScript to your FLA or AS file var my_xml XML new XML login username hank username password rudolph password login if my_xml firstChild hasChildNodes use firstChild to iterate through the child nodes of rootNode for var aNode XMLNode my_x...

Page 460: ...wing code shows XML prototype ignoreWhite true Example The following example loads an XML file with a text node that contains only white space the foyer tag comprises fourteen space characters To run this example create a text file named flooring xml and copy the following tags into it house kitchen ceramic tile kitchen bathroom linoleum bathroom foyer foyer house Create a new Flash document named...

Page 461: ...age my_xml insertBefore childNode XMLNode beforeNode XMLNode Void Parameters childNode The XMLNode object to be inserted beforeNode The XMLNode object before the insertion point for the childNode Returns Nothing Description Method inserts a new child node into the XML object s child list before the beforeNode node If the beforeNode parameter is undefined or null the node is added using the appendC...

Page 462: ...g with the last item in the node s child list and ending with the first child of the node s child list create a new XML document var doc XML new XML create a root node var rootNode XMLNode doc createElement rootNode create three child nodes var oldest XMLNode doc createElement oldest var middle XMLNode doc createElement middle var youngest XMLNode doc createElement youngest add the rootNode as the...

Page 463: ...tBefore XML removeNode XMLNode class XML load Availability Flash Player 5 behavior changed in Flash Player 7 Usage my_xml load url String Void Parameters url A string that represents the URL where the XML document to be loaded is located If the SWF file that issues this call is running in a web browser url must be in the same domain as the SWF file for details see the Description section Returns N...

Page 464: ...ject previously contained any XML trees they are discarded You can define a custom function that executes when the onLoad event handler of the XML object is invoked Example The following simple example uses the XML load method create a new XML object var flooring XML new XML set the ignoreWhite property to true default value is false flooring ignoreWhite true After loading is complete trace the XM...

Page 465: ...nextSibling Availability Flash Player 5 Usage my_xml nextSibling XMLNode Description Read only property an XMLNode value that references the next sibling in the parent node s child list This property is null if the node does not have a next sibling node This property cannot be used to manipulate child nodes use the appendChild insertBefore and removeNode methods to manipulate child nodes Example T...

Page 466: ...Node doc createElement rootNode place the new node into the XML tree doc appendChild myNode create an XML text node using createTextNode var myTextNode XMLNode doc createTextNode textNode place the new node into the XML tree myNode appendChild myTextNode trace myNode nodeName trace myTextNode nodeName output rootNode null The following example creates a new XML packet If the root node has child no...

Page 467: ...he nodeType is a numeric value from the NodeType enumeration in the W3C DOM Level 1 recommendation www w3 org TR 1998 REC DOM Level 1 19981001 level one core html The following table lists the values In Flash Player the built in XML class only supports 1 ELEMENT_NODE and 3 TEXT_NODE Integer value Defined constant 1 ELEMENT_NODE 2 ATTRIBUTE_NODE 3 TEXT_NODE 4 CDATA_SECTION_NODE 5 ENTITY_REFERENCE_N...

Page 468: ...ace the new node into the XML tree myNode appendChild myTextNode trace myNode nodeType trace myTextNode nodeType output 1 3 See also XML nodeValue XML nodeValue Availability Flash Player 5 Usage my_xml nodeValue Node Description Property the node value of the XML object If the XML object is a text node the nodeType is 3 and the nodeValue is the text of the node If the XML object is an XML element ...

Page 469: ...ty and firstChild nodeValue When you use firstChild to display contents of the node it maintains the amp entity However when you explicitly use nodeValue it converts to the ampersand character var my_xml XML new XML login username morton username password good amp evil password login trace using firstChild for var i 0 i my_xml firstChild childNodes length i trace t my_xml firstChild childNodes i f...

Page 470: ...ring that contains XML text downloaded from the server unless an error occurs during the download in which case the src parameter is undefined By default the XML onData event handler invokes XML onLoad You can override the XML onData event handler with custom behavior but XML onLoad is not called unless you call it in your implementation of XML onData Example The following example shows what the X...

Page 471: ...The following example includes ActionScript for a simple e commerce storefront application The sendAndLoad method transmits an XML element that contains the user s name and password and uses an XML onLoad handler to process the reply from the server var login_str String login username username_txt text password password_txt text var my_xml XML new XML login_str var myLoginReply_xml XML new XML myL...

Page 472: ...in first child is the login node var rootNode XMLNode my_xml firstChild first child of the root is the username node var targetNode XMLNode rootNode firstChild trace the parent node of targetNode nodeName is targetNode parentNode nodeName trace contents of the parent node are n targetNode parentNode output line breaks added for clarity the parent node of username is login contents of the parent no...

Page 473: ...ttributes name output California XML previousSibling Availability Flash Player 5 Usage my_xml previousSibling XMLNode Description Read only property an XMLNode value that references the previous sibling in the parent node s child list The property has a value of null if the node does not have a previous sibling node This property cannot be used to manipulate child nodes use the XML appendChild XML...

Page 474: ...ified XML object and its descendant nodes var xml_str String state name California city San Francisco city state var my_xml XML new XML xml_str var cityNode XMLNode my_xml firstChild firstChild trace before XML removeNode n my_xml cityNode removeNode trace trace after XML removeNode n my_xml output line breaks added for clarity before XML removeNode state name California city San Francisco city st...

Page 475: ...GET method Example The following example defines an XML packet and sets the content type for the XML object The data is then sent to a server and shows a result in a browser window var my_xml XML new XML highscore name Ernie name score 13045 score highscore my_xml contentType text xml my_xml send http www flash mx com mm highscore cfm _blank See also XML sendAndLoad XML sendAndLoad Availability Fl...

Page 476: ...ing the loaded property is set to true if the data successfully loaded and the onLoad event handler is invoked The XML data is not parsed until it is completely downloaded If the XML object previously contained any XML trees they are discarded Example The following example includes ActionScript for a simple e commerce storefront application The XML sendAndLoad method transmits an XML element that ...

Page 477: ...as not properly terminated 9 A start tag was not matched with an end tag 10 An end tag was encountered without a matching start tag Example The following example loads an XML packet into a SWF file A status message displays depending on whether the XML loads and parses successfully Add the following ActionScript to your FLA or AS file var my_xml XML new XML my_xml onLoad function success Boolean i...

Page 478: ... with an end tag break case 10 errorMessage An end tag was encountered without a matching start tag break default errorMessage An unknown error has occurred break trace status my_xml status errorMessage else trace Unable to load parse XML status my_xml status my_xml load http www flash mx com mm badxml xml XML toString Availability Flash Player 5 Usage my_xml toString String Parameters None Return...

Page 479: ... is parsed into an XML object this property is set to the text of the document s XML declaration This property is set using a string representation of the XML declaration not an XML node object If no XML declaration is encountered during a parse operation the property is set to undefined XML The XML toString method outputs the contents of the XML xmlDecl property before any other text in the XML o...

Page 480: ...y_xml xmlDecl newline newline my_txt text contentType newline my_xml contentType newline newline my_txt text docTypeDecl newline my_xml docTypeDecl newline newline my_txt text packet newline my_xml toString newline newline else my_txt text Unable to load remote XML newline newline my_txt text loaded in elapsedTime ms my_xml load http www flash mx com crossdomain xml var startTime Number getTimer S...

Page 481: ...s entries See also XML class Property method or collection Corresponding XML class entry appendChild XML appendChild attributes XML attributes childNodes XML childNodes cloneNode XML cloneNode firstChild XML firstChild hasChildNodes XML hasChildNodes insertBefore XML insertBefore lastChild XML lastChild nextSibling XML nextSibling nodeName XML nodeName nodeType XML nodeType nodeValue XML nodeValue...

Page 482: ...o TCP port numbers greater than or equal to 1024 One consequence of this restriction is that the server daemons that communicate with the XMLSocket object must also be assigned to port numbers greater than or equal to 1024 Port numbers below 1024 are often used by system services such as FTP Telnet and HTTP so XMLSocket objects are barred from these ports for security reasons The port number restr...

Page 483: ...an XMLSocket object var socket XMLSocket new XMLSocket XMLSocket close Availability Flash Player 5 Usage myXMLSocket close Void Method Description XMLSocket close Closes an open socket connection XMLSocket connect Establishes a connection to the specified server XMLSocket send Sends an XML object to the server Event handler Description XMLSocket onClose Invoked when an XMLSocket connection is clos...

Page 484: ...lified DNS domain name or an IP address in the form aaa bbb ccc ddd You can also specify null to connect to the host server on which the SWF file resides If the SWF file issuing this call is running in a web browser host must be in the same domain as the SWF file for details see Description port A number the TCP port number on the host used to establish a connection The port number must be 1024 or...

Page 485: ...F file that is being accessed For more information see Applying Flex Security in Developing Flex Applications When load is executed the XML object property loaded is set to false When the XML data finishes downloading the loaded property is set to true and the onLoad event handler is invoked The XML data is not parsed until it is completely downloaded If the XML object previously contained any XML...

Page 486: ...you must assign a function containing custom actions Example The following example executes a trace statement if an open connection is closed by the server var socket XMLSocket new XMLSocket socket connect null 2000 socket onClose function trace Connection to server lost See also function XMLSocket onConnect XMLSocket onConnect Availability Flash Player 5 Usage myXMLSocket onConnect function succe...

Page 487: ...iption Event handler invoked when a message has been downloaded from the server terminated by a zero 0 byte You can override XMLSocket onData to intercept the data sent by the server without parsing it as XML This is a useful if you re transmitting arbitrarily formatted data packets and you d prefer to manipulate the data directly when it arrives rather than have Flash Player parse the data as XML...

Page 488: ... was established if this is the first message received Each batch of parsed XML is treated as a single XML document and passed to the onXML method The default implementation of this method performs no actions To override the default implementation you must assign a function containing actions that you define Example The following function overrides the default implementation of the onXML method in...

Page 489: ...ately but the data may be transmitted at a later time The XMLSocket send method does not return a value indicating whether the data was successfully transmitted If the myXMLSocket object is not connected to the server using XMLSocket connect the XMLSocket send operation will fail Example The following example shows how you could specify a user name and password to send the XML object my_xml to the...

Page 490: ...r that you can use in a Macromedia Flex application However many items described in this chapter are not for use in typical Flex applications and should be used only as necessary For more information on the items that Macromedia recommends that you use in a Flex application see Flex ActionScript and MXML API Reference ...

Page 491: ...the following example the playMP3 function is defined The TextField object list_txt is created and set so HTML text can be rendered The text Track 1 and Track 2 are links inside the text field The playMP3 function is called when the user clicks either link and plays the MP3 that is passed as a parameter of the asfunction call var myMP3 Sound new Sound function playMP3 mp3 String myMP3 loadSound mp...

Page 492: ...mmary for the Camera class Property summary for the Camera class Method Description Camera get Returns a default or specified Camera object or null if the camera is not available Camera setMode Sets aspects of the camera capture mode including height width and frames per second Camera setMotionLevel Specifies how much motion is required to invoke Camera onActivity true and how much time should ela...

Page 493: ...Otherwise it is undefined Camera motionLevel The amount of motion required to invoke Camera onActivity true Camera motionTimeOut The number of milliseconds between the time when the camera stops detecting motion and the time Camera onActivity false is invoked Camera muted A Boolean value that specifies whether the user has allowed or denied access to the camera Camera name The name of the camera a...

Page 494: ...bandwidth Availability Flash Player 6 Usage active_cam bandwidth Number Description Read only property an integer that specifies the maximum amount of bandwidth the current outgoing video feed can use in bytes A value of 0 means that Flash video can use as much bandwidth as needed to maintain the desired frame quality To set this property use Camera setQuality Example The following example changes...

Page 495: ...property cannot be set however you can use the Camera setMode method to set a related property Camera fps which specifies the maximum frame rate at which you would like the camera to capture data Example The following example detects the rate in frames per second that the camera captures data using the currentFps property var my_video Video var fps_pb mx controls ProgressBar var my_cam Camera Came...

Page 496: ...e rate in frames per second that the camera captures data using the currentFps property var my_video Video var fps_pb mx controls ProgressBar var my_cam Camera Camera get my_video attachVideo my_cam this onEnterFrame function fps_pb setProgress my_cam fps my_cam currentFps my_cam fps fps_pb setStyle fontSize 10 fps_pb setStyle themeColor haloOrange fps_pb labelPlacement top fps_pb mode manual fps_...

Page 497: ...e to the default camera By means of the Camera settings panel discussed later in this section the user can specify the default camera Flash should use If you pass a value for index you might be trying to reference a camera other than the one the user prefers You might use index in rare cases for example if your application is capturing video from two cameras at the same time When a SWF file tries ...

Page 498: ...The following example lets you select an active camera to use from a ComboBox instance The current active camera is displayed in a Label instance var my_cam Camera Camera get var my_video Video my_video attachVideo my_cam var camera_lbl mx controls Label var cameras_cb mx controls ComboBox camera_lbl text my_cam name cameras_cb dataProvider Camera names function changeCamera Void my_cam Camera get...

Page 499: ...eflected in the array returned by Camera names Example The following example displays an array of cameras in a text field that is created at runtime and tells you which camera you are currently using var camera_lbl mx controls Label var my_cam Camera Camera get var my_video Video my_video attachVideo my_cam camera_lbl text my_cam index my_cam name this createTextField cameras_txt this getNextHighe...

Page 500: ...ion 3 var motionLevel_lbl mx controls Label configure the NumericStepper component instance var motionLevel_nstep mx controls NumericStepper motionLevel_nstep minimum 0 motionLevel_nstep maximum 100 motionLevel_nstep stepSize 5 motionLevel_nstep value my_cam motionLevel Continuously update the progress of the ProgressBar component instance to the activityLevel of the current Camera instance which ...

Page 501: ..._cam motionTimeOut Number Description Read only property the number of milliseconds between the time the camera stops detecting motion and the time Camera onActivity false is invoked The default value is 2000 2 seconds To set this value use Camera setMotionLevel Example In the following example the ProgressBar instance changes its halo theme color when the activity level falls below the motion lev...

Page 502: ...nly property a Boolean value that specifies whether the user has denied access to the camera true or allowed access false in the Flash Player Privacy Settings panel When this value changes Camera onStatus is invoked For more information see Camera get Example In the following example an error message could be displayed if my_cam muted evaluates to true var my_cam Camera Camera get var my_video Vid...

Page 503: ...ilability Flash Player 6 Usage Camera names Array Note The correct syntax is Camera names To assign the return value to a variable use syntax like cam_array Camera names To determine the name of the current camera use active_cam name Description Read only class property retrieves an array of strings reflecting the names of all available cameras without displaying the Flash Player Privacy Settings ...

Page 504: ... Parameters activity A Boolean value set to true when the camera starts detecting motion false when it stops Returns Nothing Description Event handler invoked when the camera starts or stops detecting motion If you want to respond to this event handler you must create a function to process its activity value To specify the amount of motion required to invoke Camera onActivity true and the amount o...

Page 505: ...se and this handler is invoked with an information object whose code property is Camera Unmuted and whose level property is Status If the user denies access the Camera muted property is set to true and this handler is invoked with an information object whose code property is Camera Muted and whose level property is Status To determine whether the user has denied or allowed access to the camera wit...

Page 506: ...e from 1 lowest quality maximum compression to 100 highest quality no compression The default value is 0 which means that picture quality can vary as needed to avoid exceeding available bandwidth Example The following example uses a NumericStepper instance to specify the amount of compression applied to the camera feed var quality_nstep mx controls NumericStepper var my_cam Camera Camera get var m...

Page 507: ...ive mode that best meets the specified requirements If the camera does not have a native mode that matches all the parameters you pass Flash selects a capture mode that most closely synthesizes the requested mode This manipulation may involve cropping the image and dropping frames By default Flash drops frames as needed to maintain image size To minimize the number of dropped frames even if this m...

Page 508: ...specifies how many milliseconds must elapse without activity before Flash considers activity to have stopped and invokes the Camera onActivity false event handler The default value is 2000 2 seconds Returns Nothing Description Method specifies how much motion is required to invoke Camera onActivity true Optionally sets the number of milliseconds that must elapse without activity before Flash consi...

Page 509: ...width When an audio stream is considered silent no audio data is sent Instead a single message is sent indicating that silence has started Camera setMotionLevel is designed to detect motion and does not affect bandwidth usage Even if a video stream does not detect motion video is still sent Example The following example writes to the log file when video activity starts or stops Change the motion s...

Page 510: ...recedence pass a value for bandwidth and 0 for frameQuality Flash will transmit video at the highest quality possible within the specified bandwidth If necessary Flash will reduce picture quality to avoid exceeding the specified bandwidth In general as motion increases quality decreases To indicate that quality takes precedence pass 0 for bandwidth and a numeric value for frameQuality Flash will u...

Page 511: ...code displays the current width height and FPS of a video instance in a Label component instance on the Stage var my_cam Camera Camera get var my_video Video my_video attachVideo my_cam var dimensions_lbl mx controls Label dimensions_lbl setStyle fontSize 9 dimensions_lbl setStyle fontWeight bold dimensions_lbl setStyle textAlign center dimensions_lbl text width my_cam width height my_cam height F...

Page 512: ...cription Constructor creates a Color object for the movie clip specified by the target_mc parameter You can then use the methods of that Color object to change the color of the entire target movie clip Example The following example creates a Color object called my_color for the movie clip my_mc and sets its RGB value to orange var my_color Color new Color my_mc my_color setRGB 0xff9933 Method Desc...

Page 513: ...e value to a hexadecimal string and assigns it to the myValue variable var my_color Color new Color my_mc set the color my_color setRGB 0xff9933 var myValue String my_color getRGB toString 16 trace the color value trace myValue traces ff9933 See also Color setRGB Color getTransform Availability Flash Player 5 Usage my_color getTransform Object Parameters None Returns An object whose properties con...

Page 514: ...m Color setRGB Availability Flash Player 5 Usage my_color setRGB 0xRRGGBB Number Void Parameters 0xRRGGBB The hexadecimal or RGB color to be set RR GG and BB each consist of two hexadecimal digits that specify the offset of each color component The 0x tells the ActionScript compiler that the number is a hexadecimal value Description Method specifies an RGB color for a Color object Calling this met...

Page 515: ...r a color transform object correspond to the settings in the Advanced Effect dialog box and are defined as follows ra is the percentage for the red component 100 to 100 rb is the offset for the red component 255 to 255 ga is the percentage for the green component 100 to 100 gb is the offset for the green component 255 to 255 ba is the percentage for the blue component 100 to 100 bb is the offset f...

Page 516: ...s the colorTransformObject to a Color object Create a color object called my_color for the target my_mc var my_color Color new Color my_mc Create a color transform object called myColorTransform using Set the values for myColorTransform var myColorTransform Object ra 50 rb 244 ga 40 gb 112 ba 12 bb 90 aa 40 ab 70 Associate the color transform object with the Color object created for my_mc my_color...

Page 517: ...t click in Flash Player the edit menu which appears when you right click over a selectable or editable text field and an error menu which appears when a SWF file has failed to load into Flash Player Only the standard and edit menus can be modified with the ContextMenu class Custom menu items always appear at the top of the Flash Player context menu above any visible built in menu items a separator...

Page 518: ...e or based on the type of object movie clip text field or button or the Timeline that the user right clicks or Control clicks For an example of creating an event handler see ContextMenu onSelect Example The following example hides all the built in objects in the Context menu However the Settings and About items still appear because they cannot be disabled var newMenu ContextMenu new ContextMenu ne...

Page 519: ...ion Property an object that has the following Boolean properties zoom quality play loop rewind forward_back and print Setting these variables to false removes the corresponding menu items from the specified ContextMenu object These properties are enumerable and are set to true by default Example In this example the built in Quality and Print menu items are disabled for the ContextMenu object my_cm...

Page 520: ...built in menu items are hidden and adds a menu item with the text Save It then creates a copy of my_cm and assigns it to the variable clone_cm which inherits all the properties of the original menu var my_cm ContextMenu new ContextMenu my_cm hideBuiltInItems var menuItem_cmi ContextMenuItem new ContextMenuItem Save saveHandler my_cm customItems push menuItem_cmi function saveHandler obj menuItem s...

Page 521: ...textMenuItem class entry Example The following example creates a new custom menu item called menuItem_cm with a caption of Send e mail and a callback handler named emailHandler The new menu item is then added to the ContextMenu object my_cm using the customItems array Finally the new menu is attached to a movie clip named email_mc var my_cm ContextMenu new ContextMenu var menuItem_cmi ContextMenuI...

Page 522: ... items are hidden except for Print The menu object is attached to the current Timeline var my_cm ContextMenu new ContextMenu my_cm hideBuiltInItems my_cm builtInItems print true this menu my_cm ContextMenu onSelect Availability Flash Player 7 Usage my_cm onSelect function item Object item_menu ContextMenu Void your code here Parameters item A reference to the object movie clip button or selectable...

Page 523: ...context menu was invoked my_cm new ContextMenu function menuHandler obj Object menu ContextMenu if obj instanceof MovieClip trace Movie clip obj if obj instanceof TextField trace Text field obj if obj instanceof Button trace Button obj my_cm onSelect menuHandler my_mc menu my_cm my_btn menu my_cm ...

Page 524: ...racters newlines and other white space characters are ignored No item can be more than 100 characters long Items that are identical to any built in menu item or to another custom item are ignored whether the matching item is visible or not Menu items are compared without regard to case punctuation or white space None of the following words can appear in a custom item Macromedia Flash Player or Set...

Page 525: ...t value is true This parameter is optional visible A Boolean value that indicates whether the menu item is visible or invisible The default value is true This parameter is optional Returns A reference to a ContextMenuItem object Description Constructor creates a new ContextMenuItem object that can be added to the ContextMenu customItems array Example This example adds Start and Stop menu items sep...

Page 526: ...xtMenuItem copy Availability Flash Player 7 Usage menuItem_cmi copy ContextMenuItem Returns A ContextMenuItem object Description Method creates and returns a copy of the specified ContextMenuItem object The copy includes all properties of the original object Example This example creates a new ContextMenuItem object named original_cmi with the caption Pause and a callback handler set to the functio...

Page 527: ... Stop is selected the number of milliseconds that have elapsed since the SWF file started is traced The Start menu item is re enabled and the Stop menu item is disabled var my_cm ContextMenu new ContextMenu var startMenuItem ContextMenuItem new ContextMenuItem Start startHandler startMenuItem enabled true my_cm customItems push startMenuItem var stopMenuItem ContextMenuItem new ContextMenuItem Sto...

Page 528: ...ves two parameters obj a reference to the object under the mouse when the user invoked the Flash Player context menu and item a reference to the ContextMenuItem object that represents the selected menu item Example The following example assigns a function to the onSelect handler for a ContextMenuItem object named my_cmi The function writes the caption of the selected menu item to the log file var ...

Page 529: ...s array Finally the menu is attached to the current Timeline of the SWF file var my_cm ContextMenu new ContextMenu var open_cmi ContextMenuItem new ContextMenuItem Open itemHandler var save_cmi ContextMenuItem new ContextMenuItem Save itemHandler var print_cmi ContextMenuItem new ContextMenuItem Print itemHandler print_cmi separatorBefore true my_cm customItems push open_cmi save_cmi print_cmi fun...

Page 530: ...ible and the Stop menu item is made invisible var my_cm ContextMenu new ContextMenu var startMenuItem ContextMenuItem new ContextMenuItem Start startHandler startMenuItem visible true my_cm customItems push startMenuItem var stopMenuItem ContextMenuItem new ContextMenuItem Stop stopHandler true stopMenuItem visible false my_cm customItems push stopMenuItem function stopHandler obj item trace Stopp...

Page 531: ...n the original movie clip are not copied into the duplicate movie clip Use the removeMovieClip function or method to delete a movie clip instance created with duplicateMovieClip Example In the following example a new movie clip instance is created called img_mc An image is loaded into the movie clip and then the img_mc clip is duplicated The duplicated clip is called newImg_mc and this new clip is...

Page 532: ...nces Note If you use a component then FocusManager overrides Flash Player s focus handling including use of this global property Example The following example demonstrates how to hide the yellow rectangle around any instances in a SWF file when they have focus in a browser window Create some buttons or movie clips and add the following ActionScript _focusrect false Change the publish settings to F...

Page 533: ...eturns The value of the specified property Description Function returns the value of the specified property for the movie clip my_mc Example The following example creates a new movie clip someClip_mc and shows the alpha value _alpha for the movie clip someClip_mc in the Output panel this createEmptyMovieClip someClip_mc 999 trace The alpha of getProperty someClip_mc _name is getProperty someClip_m...

Page 534: ...e Microphone class Method Description Microphone get Returns a default or specified Microphone object or null if the microphone is not available Microphone setGain Specifies the amount by which the microphone should boost the signal Microphone setRate Specifies the rate at which the microphone should capture sound in kHz Microphone setSilenceLevel Specifies the amount of sound required to activate...

Page 535: ...vity level of the current microphone in a ProgressBar instance called activityLevel_pb var activityLevel_pb mx controls ProgressBar activityLevel_pb mode manual Microphone names Class property an array of strings reflecting the names of all available sound capture devices including sound cards and microphones Microphone rate The sound capture rate in kHz Microphone silenceLevel The amount of sound...

Page 536: ...ilability Flash Player 6 Usage active_mic gain Number Description Read only property the amount by which the microphone boosts the signal Valid values are 0 to 100 The default value is 50 Example The following example uses a ProgressBar instance called gain_pb to display and a NumericStepper instance called gain_nstep to set the microphone s gain value this createEmptyMovieClip sound_mc this getNe...

Page 537: ...ce the same microphone Thus if your script contains the lines mic1 Microphone get and mic2 Microphone get both mic1 and mic2 reference the same default microphone In general you shouldn t pass a value for index simply use the Microphone get method to return a reference to the default microphone By means of the Microphone settings panel discussed later in this section the user can specify the defau...

Page 538: ...e user specify the default microphone and then captures audio and plays it back locally To avoid feedback you may want to test this code while wearing headphones this createEmptyMovieClip sound_mc this getNextHighestDepth System showSettings 2 var active_mic Microphone Microphone get sound_mc attachAudio active_mic See also Microphone index Microphone muted Microphone names Microphone onStatus Mov...

Page 539: ...sage active_mic muted Boolean Description Read only property a Boolean value that specifies whether the user has denied access to the microphone true or allowed access false When this value changes Microphone onStatus is invoked For more information see Microphone get Example This example gets the default microphone and checks whether it is muted var active_mic Microphone Microphone get trace acti...

Page 540: ...he current microphone use active_mic name Description Read only class property retrieves an array of strings reflecting the names of all available sound capture devices without displaying the Flash Player Privacy Settings panel This array behaves the same as any other ActionScript array implicitly providing the zero based index of each sound capture device and the number of sound capture devices o...

Page 541: ... Description Event handler invoked when the microphone starts or stops detecting sound If you want to respond to this event handler you must create a function to process its activity value To specify the amount of sound required to invoke Microphone onActivity true and the amount of time that must elapse without sound before Microphone onActivity false is invoked use Microphone setSilenceLevel Exa...

Page 542: ...s access to the microphone If you want to respond to this event handler you must create a function to process the information object generated by the microphone When a SWF file tries to access the microphone Flash Player displays a Privacy dialog box that lets the user choose whether to allow or deny access If the user allows access the Microphone muted property is set to false and this event hand...

Page 543: ...Clip sound_mc this getNextHighestDepth var active_mic Microphone Microphone get sound_mc attachAudio active_mic active_mic onStatus function infoObj Object status_txt _visible active_mic muted muted_txt htmlText Status a href asfunction System showSettings u infoObj code u a this createTextField status_txt this getNextHighestDepth 0 0 100 22 status_txt html true status_txt autoSize true status_txt...

Page 544: ...x i break function changeRate active_mic setRate rate_cb selectedItem rate_lbl text Current rate active_mic rate kHz rate_cb addEventListener change changeRate rate_lbl text Current rate active_mic rate kHz See also Microphone setRate Microphone setGain Availability Flash Player 6 Usage active_mic setGain gain Number Void Parameters gain An integer that specifies the amount by which the microphone...

Page 545: ...pb setProgress active_mic gain 100 gain_nstep value active_mic gain function changeGain active_mic setGain gain_nstep value gain_pb setProgress active_mic gain 100 gain_nstep addEventListener change changeGain See also Microphone gain Microphone setUseEchoSuppression Microphone setRate Availability Flash Player 6 Usage active_mic setRate kHz Number Void Parameters kHz The rate at which the microph...

Page 546: ...r rate_array rate_cb labelFunction function item Object return item kHz for var i 0 i rate_array length i if rate_cb getItemAt i active_mic rate rate_cb selectedIndex i break function changeRate active_mic setRate rate_cb selectedItem rate_lbl text Current rate active_mic rate kHz rate_cb addEventListener change changeRate rate_lbl text Current rate active_mic rate kHz See also Microphone rate Mic...

Page 547: ...ilence value This method is similar in purpose to Camera setMotionLevel both methods are used to specify when the onActivity event handler should be invoked However these methods have a significantly different impact on publishing streams Camera setMotionLevel is designed to detect motion and does not affect bandwidth usage Even if a video stream does not detect motion video is still sent Micropho...

Page 548: ...he example for Camera setMotionLevel See also Microphone activityLevel Microphone onActivity Microphone setGain Microphone silenceLevel Microphone silenceTimeOut Microphone setUseEchoSuppression Availability Flash Player 6 Usage active_mic setUseEchoSuppression suppress Boolean Void Parameters suppress A Boolean value indicating whether echo suppression should be used true or not false Returns Not...

Page 549: ...t sound_mc attachAudio active_mic activityLevel_pb mode manual activityLevel_pb label Activity Level 3 useEchoSuppression_ch selected active_mic useEchoSuppression this onEnterFrame function activityLevel_pb setProgress active_mic activityLevel 100 var chListener Object new Object chListener click function evt Object active_mic setUseEchoSuppression evt target selected useEchoSuppression_ch addEve...

Page 550: ...e nstepListener this onEnterFrame function silenceLevel_pb setProgress active_mic activityLevel 100 active_mic onActivity function active Boolean if active silenceLevel_pb indeterminate false silenceLevel_pb setStyle themeColor haloGreen silenceLevel_pb label Activity level 3 else silenceLevel_pb indeterminate true silenceLevel_pb setStyle themeColor 0xFF0000 silenceLevel_pb label Activity level i...

Page 551: ...enceLevel_pb label Activity level 3 silenceLevel_pb mode manual silenceTimeOut_nstep minimum 0 silenceTimeOut_nstep maximum 10 silenceTimeOut_nstep value active_mic silenceTimeOut 1000 var nstepListener Object new Object nstepListener change function evt Object active_mic setSilenceLevel active_mic silenceLevel evt target value 1000 silenceTimeOut_nstep addEventListener change nstepListener this o...

Page 552: ...udio stream var useEchoSuppression_ch mx controls CheckBox var activityLevel_pb mx controls ProgressBar this createEmptyMovieClip sound_mc this getNextHighestDepth var active_mic Microphone Microphone get sound_mc attachAudio active_mic activityLevel_pb mode manual activityLevel_pb label Activity Level 3 useEchoSuppression_ch selected active_mic useEchoSuppression this onEnterFrame function activi...

Page 553: ... macromedia com go jsapi_info_en Example The following command will output the number of items in the library of the current document to the trace window You must run this example as a Flash panel because Flash files can t call MMExecute if they are run in either test movie or the browser Place the following code into frame 1 of the main Timeline of an empty Flash document var numLibItems MMExecut...

Page 554: ...Clip Creates an empty movie clip MovieClip createTextField Creates an empty text field MovieClip duplicateMovieClip Duplicates the specified movie clip MovieClip getBounds Returns the minimum and maximum x and y coordinates of a SWF file in a specified coordinate space MovieClip getBytesLoaded Returns the number of bytes loaded for the specified movie clip MovieClip getBytesTotal Returns the size ...

Page 555: ...ends the playhead to the previous frame of the movie clip MovieClip removeMovieClip Removes the movie clip from the Timeline if it was created with duplicateMovieClip MovieClip duplicateMovieClip or MovieClip attachMovie MovieClip setMask Sets a movie clip as the mask for the specified movie clip MovieClip startDrag Specifies a movie clip as draggable and begins dragging the movie clip MovieClip s...

Page 556: ...t MovieClip _framesloaded Read only the number of frames that have been loaded from a streaming SWF file MovieClip _height The height of a movie clip instance in pixels MovieClip hitArea A reference to a movie clip that serves as the hit area for another movie clip MovieClip _lockroot The specification of what _root refers to when a SWF file is loaded into a movie clip MovieClip menu An object tha...

Page 557: ...he percentage that the movie clip is scaled horizontally MovieClip _y The y coordinate of a movie clip instance MovieClip _ymouse Read only the y coordinate of the mouse pointer within a movie clip instance MovieClip _yscale The value specifying the percentage for vertically scaling a movie clip Event handler Description MovieClip onData Invoked when all the data is loaded into a movie clip MovieC...

Page 558: ...mage_mc holder_mc getNextHighestDepth MovieClip onLoad Invoked when the movie clip is instantiated and appears in the Timeline MovieClip onMouseDown Invoked when the left mouse button is pressed MovieClip onMouseMove Invoked every time the mouse is moved MovieClip onMouseUp Invoked when the left mouse button is released MovieClip onPress Invoked when the mouse is pressed while the pointer is over ...

Page 559: ...audio source to be played To stop playing the audio source pass false for source You can extend the methods and event handlers of the MovieClip class by creating a subclass Example The following code creates a new NetStream connection Add a new Video symbol by opening the Library panel and selecting New Video from the Library options menu Give it the instance name my_video Dynamically load the FLV...

Page 560: ...s Video attachVideo MovieClip attachMovie Availability Flash Player 5 Usage my_mc attachMovie idName String newName String depth Number initObject Object MovieClip Parameters idName The linkage name of the movie clip symbol in the library to attach to a movie clip on the Stage This is the name entered in the Identifier field in the Linkage Properties dialog box newname A unique instance name for t...

Page 561: ...vieClip MovieClip beginFill Availability Flash Player 6 Usage my_mc beginFill rgb Number alpha Number Void Parameter rgb A hex color value for example red is 0xFF0000 blue is 0x0000FF and so on If this value is not provided or is undefined a fill is not created alpha An integer between 0 100 that specifies the alpha value of the fill If this value is not provided 100 solid is used If the value is ...

Page 562: ... blue is 0x0000FF and so on alphas An array of alpha values for the corresponding colors in the colors array valid values are 0 100 If the value is less than 0 Flash uses 0 If the value is greater than 100 Flash uses 100 ratios An array of color distribution ratios valid values are 0 255 This value defines the percentage of the width where the color is sampled at 100 percent matrix A transformatio...

Page 563: ...t clip for the upper left corner of the gradient y is the vertical position relative to the registration point of the parent clip for the upper left corner of the gradient w is the width of the gradient h is the height of the gradient and r is the rotation in radians of the gradient The following example uses a beginGradientFill method with a matrix parameter that is an object with these propertie...

Page 564: ...ng conditions exist The number of items in the colors alphas and ratios parameters are not equal The fillType parameter is not linear or radial Any of the fields in the object for the matrix parameter are missing or invalid You can extend the methods and event handlers of the MovieClip class by creating a subclass Example The following code uses both methods to draw two stacked rectangles with a r...

Page 565: ...ters None Returns Nothing Description Method removes all the graphics created during runtime using the movie clip draw methods including line styles specified with MovieClip lineStyle Shapes and lines that are manually drawn during authoring time with the Flash drawing tools are unaffected Example The following example draws a box on the Stage When the user clicks the box graphic it removes the gr...

Page 566: ... clip Returns A reference to the newly created movie clip Description Method creates an empty movie clip as a child of an existing movie clip This method behaves similarly to the attachMovie method but you don t need to provide an external linkage identifier for the new movie clip The registration point for a newly created empty movie clip is the upper left corner This method fails if any of the p...

Page 567: ... depth parameter determines the new text field s z order position in the movie clip Each position in the z order can contain only one object If you create a new text field on a depth that already has a text field the new text field will replace the existing text field To avoid overwriting existing text fields use the MovieClip getInstanceAtDepth to determine whether a specific depth is already occ...

Page 568: ... can extend the methods and event handlers of the MovieClip class by creating a subclass Example The following example creates a text field with a width of 300 a height of 100 an x coordinate of 100 a y coordinate of 100 no border red and underlined text this createTextField my_txt 1 100 100 300 100 my_txt multiline true my_txt wordWrap true var my_fmt TextFormat new TextFormat my_fmt color 0xFF00...

Page 569: ...the parent movie clip anchorX An integer that specifies the horizontal position of the next anchor point relative to the registration point of the parent movie clip anchorY An integer that specifies the vertical position of the next anchor point relative to the registration point of the parent movie clip Returns Nothing Description Method draws a curve using the current line style from the current...

Page 570: ...he Math class this createEmptyMovieClip circle2_mc 2 circle2_mc lineStyle 0 0x000000 drawCircle circle2_mc 10 10 100 function drawCircle mc MovieClip x Number y Number r Number Void mc moveTo x r y mc curveTo r x Math tan Math PI 8 r y Math sin Math PI 4 r x Math sin Math PI 4 r y mc curveTo Math tan Math PI 8 r x r y x r y mc curveTo Math tan Math PI 8 r x r y Math sin Math PI 4 r x Math sin Math...

Page 571: ...lowing example evaluates the _droptarget property of the garbage_mc movie clip instance and uses eval to convert it from slash syntax to a dot syntax reference The garbage_mc reference is then compared to the reference to the trashcan_mc movie clip instance If the two references are equivalent the visibility of garbage_mc is set to false If they are not equivalent the garbage instance resets to it...

Page 572: ...ys start playing at Frame 1 no matter what frame the original movie clip is on when the duplicateMovieClip method is called Variables in the parent movie clip are not copied into the duplicate movie clip Movie clips that have been created using duplicateMovieClip are not duplicated if you call duplicateMovieClip on their parent If the parent movie clip is deleted the duplicate movie clip is also d...

Page 573: ...bled is set to false the object is not included in automatic tab ordering Example The following example disables the circle_mc movie clip when the user clicks it circle_mc onRelease function trace disabling the this _name movie clip this enabled false MovieClip endFill Availability Flash Player 6 Usage my_mc endFill Void Parameters None Returns Nothing Description Method applies a fill to the line...

Page 574: ...ailability Flash Player 6 Usage my_mc _focusrect Boolean Description Property a Boolean value that specifies whether a movie clip has a yellow rectangle around it when it has keyboard focus This property can override the global _focusrect property The default value of the _focusrect property of a movie clip instance is null meaning the movie clip instance does not override the global _focusrect pr...

Page 575: ...this movie clip in the browser by pressing Enter or the Spacebar when _focusrect is disabled See Also _focusrect MovieClip _framesloaded Availability Flash Player 4 Usage my_mc _framesloaded Number Description Read only property the number of frames that have been loaded from a streaming SWF file This property is useful for determining whether the contents of a specific frame and all the frames be...

Page 576: ...espectively You can extend the methods and event handlers of the MovieClip class by creating a subclass Example The following example creates a movie clip called square_mc The code draws a square for that movie clip and uses MovieClip getBounds to write the coordinate values of the instance to the log file this createEmptyMovieClip square_mc 1 square_mc _x 10 square_mc _y 10 square_mc beginFill 0x...

Page 577: ...n extend the methods and event handlers of the MovieClip class by creating a subclass See also MovieClip getBytesTotal MovieClip getBytesTotal Availability Flash Player 5 Usage my_mc getBytesTotal Number Parameters None Returns An integer indicating the total size in bytes of my_mc Description Method returns the size in bytes of the movie clip specified by my_mc For movie clips that are external t...

Page 578: ...th of all movie clip instances on the Stage for var i in this if typeof this i movieclip trace movie clip this i _name is at depth this i getDepth See also MovieClip getInstanceAtDepth MovieClip getNextHighestDepth MovieClip swapDepths MovieClip getInstanceAtDepth Availability Flash Player 7 Usage my_mc getInstanceAtDepth depth Number MovieClip Parameters depth An integer that specifies the depth ...

Page 579: ...eClip getNextHighestDepth Availability Flash Player 7 Usage my_mc getNextHighestDepth Number Parameters None Returns An integer that reflects the next available depth index that would render above all other objects on the same level and layer within my_mc Description Method lets you determine a depth value that you can pass to MovieClip attachMovie MovieClip duplicateMovieClip or MovieClip createE...

Page 580: ...Flash Player version that was targeted when the SWF file loaded into my_mc was published Description Method returns an integer that indicates the Flash Player version for which my_mc was published If my_mc is a JPEG file or if an error occurs and Flash can t determine the SWF version of my_mc 1 is returned You can extend the methods and event handlers of the MovieClip class by creating a subclass ...

Page 581: ... a tab index value for static text in Flash However other products may do so for example Macromedia FlashPaper The contents of the TextSnapshot object aren t dynamic that is if the movie clip moves to a different frame or is altered in some way for example objects in the movie clip are added or removed the TextSnapshot object might not represent the current text in the movie clip To ensure that th...

Page 582: ...use one of the following reserved target names _self specifies the current frame in the current window _blank specifies a new window _parent specifies the parent of the current frame and _top specifies the top level frame in the current window variables String either GET or POST an optional parameter specifying a method for sending variables associated with the SWF file to load If there are no var...

Page 583: ...globalToLocal Availability Flash Player 5 Usage my_mc globalToLocal point Object Void Parameters point The name or identifier of an object created with the generic Object class The object specifies the x and y coordinates as properties Returns Nothing Description Method converts the point object from Stage global coordinates to the movie clip s local coordinates You can extend the methods and even...

Page 584: ...ormat Mouse addListener mouseListener See also MovieClip getBounds MovieClip localToGlobal MovieClip gotoAndPlay Availability Flash Player 5 Usage my_mc gotoAndPlay frame Object Void Parameters frame A number representing the frame number or a string representing the label of the frame to which the playhead is sent Returns Nothing Description Method starts playing the SWF file at the specified fra...

Page 585: ...ites the height and width of a movie clip to the log file this createEmptyMovieClip image_mc this getNextHighestDepth var image_mcl MovieClipLoader new MovieClipLoader var mclListener Object new Object mclListener onLoadInit function target_mc MovieClip trace target_mc _name target_mc _width X target_mc _height pixels image_mcl addListener mclListener image_mcl loadClip http www macromedia com dev...

Page 586: ...quare_mc movie clip traces that it has been clicked square_mc hitArea circle_mc square_mc onRelease function trace hit this _name You can also set the circle_mc movie clip visible property to false to hide the hit area for square_mc circle_mc _visible false See Also MovieClip hitTest MovieClip hitTest Availability Flash Player 5 Usage my_mc hitTest x Number y Number shapeFlag Boolean Boolean my_mc...

Page 587: ...ple The following example uses hitTest to determine if the movie clip circle_mc overlaps or intersects the movie clip square_mc when the user releases the mouse button square_mc onPress function this startDrag square_mc onRelease function this stopDrag if this hitTest circle_mc trace you hit the circle See also MovieClip getBounds MovieClip globalToLocal MovieClip localToGlobal MovieClip lineStyle...

Page 588: ... You can extend the methods and event handlers of the MovieClip class by creating a subclass Example The following code draws a triangle with a 5 pixel solid magenta line with no fill this createEmptyMovieClip triangle_mc 1 triangle_mc lineStyle 5 0xff00ff 100 triangle_mc moveTo 200 200 triangle_mc lineTo 300 300 triangle_mc lineTo 100 300 triangle_mc lineTo 200 200 See also MovieClip beginFill Mo...

Page 589: ... 0xFF00FF 100 triangle_mc moveTo 200 200 triangle_mc lineTo 300 300 triangle_mc lineTo 100 300 triangle_mc lineTo 200 200 triangle_mc endFill See also MovieClip beginFill MovieClip createEmptyMovieClip MovieClip endFill MovieClip lineStyle MovieClip moveTo MovieClip loadMovie Availability Flash Player 5 Loading JPEG files requires Flash Player 6 or later Usage my_mc loadMovie url String variables ...

Page 590: ...If you attach an event handler to a button using on or if you create a dynamic handler using an event handler method such as MovieClip onPress and then you call loadMovie the event handler does not remain after the new content is loaded However if you attach an event handler to a movie clip using onClipEvent or on and then call loadMovie on that movie clip the event handler remains after the new c...

Page 591: ...arameter The GET method appends the variables to the end of the URL and is used for small numbers of variables The POST method sends the variables in a separate HTTP header and is used for long strings of variables Returns Nothing Description Method reads data from an external file and sets the values for variables in my_mc The external file can be a text file generated by ColdFusion a CGI script ...

Page 592: ... is reflected after you click and drag the instance this createTextField point_txt this getNextHighestDepth 0 0 100 22 var mouseListener Object new Object mouseListener onMouseMove function var point Object x my_mc _width 2 y my_mc _height 2 my_mc localToGlobal point point_txt text x point x y point y Mouse addListener mouseListener my_mc onPress function this startDrag my_mc onRelease function th...

Page 593: ...vie set the MovieClip _lockroot property to true in the loader movie as shown in the following code If you don t set _lockroot to true in the loader movie the loader has access only to its own library but not the library in the loaded movie myMovieClip _lockroot true Example In the following example lockroot fla has _lockroot applied to the main SWF file If it is loaded into another FLA document _...

Page 594: ...t_mc _level0 nolockroot_mc lockroot_mc _level0 lockroot_mc from nolockroot swf myVar 1 i lockroot_mc dumpRoot type Function version WIN 7 0 19 0 nolockroot_mc _level0 nolockroot_mc lockroot_mc _level0 lockroot_mc from lockroot swf myOtherVar 2 myVar 1 The file with no _lockroot applied contains all of the other variables contained in the root SWF as well If you don t have access to the nolockroot ...

Page 595: ...beled View Image in Browser that has an associated function named viewImage var menu_cm ContextMenu new ContextMenu menu_cm customItems push new ContextMenuItem View Image in Browser viewImage this createEmptyMovieClip image_mc this getNextHighestDepth var mclListener Object new Object mclListener onLoadInit function target_mc MovieClip target_mc menu menu_cm var image_mcl MovieClipLoader new Movi...

Page 596: ...awing position is not changed You can extend the methods and event handlers of the MovieClip class by creating a subclass Example The following example draws a triangle with a 5 pixel solid magenta line and a partially transparent blue fill this createEmptyMovieClip triangle_mc 1 triangle_mc beginFill 0x0000FF 30 triangle_mc lineStyle 5 0xFF00FF 100 triangle_mc moveTo 200 200 triangle_mc lineTo 30...

Page 597: ...getMCInfo target_mc MovieClip obj Object trace You clicked on the movie clip target_mc _name trace t width target_mc _width height target_mc _height trace for var i in this if typeof this i movieclip this i menu menu_cm MovieClip nextFrame Availability Flash Player 5 Usage my_mc nextFrame Void Parameters None Returns Nothing Description Method sends the playhead to the next frame and stops it You ...

Page 598: ...ple illustrates the correct use of MovieClip onData and onClipEvent data symbol_mc is a movie clip symbol in the library It is linked to the MovieClip class The following function is triggered for each instance of symbol_mc when it receives data symbol_mc onData function trace The movie clip has received data dynamic_mc is a movie clip that is being loaded with MovieClip loadMovie This code attemp...

Page 599: ...n the event handler is invoked You can define the function on the Timeline or in a class file that extends the MovieClip class or is linked to a symbol in the library Example The following example defines a function for the onDragOut method that writes the results of a trace method to the log file my_mc onDragOut function trace onDragOut called See also MovieClip onDragOver MovieClip onDragOver Av...

Page 600: ...DragOut MovieClip onEnterFrame Availability Flash Player 6 Usage my_mc onEnterFrame function your statements here Parameters None Returns Nothing Description Event handler invoked repeatedly at the frame rate of the SWF file The actions associated with the enterFrame event are processed before any frame actions that are attached to the affected frames You must define a function that executes when ...

Page 601: ... must be given focus This can be done either by using Selection setFocus or by setting the Tab key to navigate to the clip If Selection setFocus is used the path for the movie clip must be passed to Selection setFocus It is very easy for other elements to take the focus back after the mouse is moved Example The following example defines a function for the onKeyDown method that writes the results a...

Page 602: ...l in the library The onKeyUp event handler works only if the movie clip has input focus enabled and set First the MovieClip focusEnabled property must be set to true for the movie clip Then the clip must be given focus This can be done either by using Selection setFocus or by setting the Tab key to navigate to the clip If Selection setFocus is used the path for the movie clip must be passed to Sel...

Page 603: ...e event handler is invoked You can define the function on the Timeline or in a class file that extends the MovieClip class or is linked to a symbol in the library Example The following example displays writes information about the movie clip that loses focus and the instance that currently has focus Two movie clips called my_mc and other_mc are on the Stage Add the following ActionScript to your A...

Page 604: ...ng example illustrates one way to use MovieClip onLoad with setInterval to check that a file has loaded into a movie clip that s created at runtime this createEmptyMovieClip tester_mc 1 tester_mc loadMovie http www yourserver com your_movie swf function checkLoaded target_mc MovieClip var pctLoaded Number target_mc getBytesLoaded target_mc getBytesTotal 100 if isNaN pctLoaded pctLoaded 0 target_mc...

Page 605: ...to a symbol in the library Example The following example defines a function for the onMouseDown method that writes the results of a trace method to the log file my_mc onMouseDown function trace onMouseDown called MovieClip onMouseMove Availability Flash Player 6 Usage my_mc onMouseMove function your statements here Parameters None Returns Nothing Description Event handler invoked when the mouse mo...

Page 606: ...tion Event handler invoked when the mouse button is released You must define a function that executes when the event handler is invoked You can define the function on the Timeline or in a class file that extends the MovieClip class or is linked to a symbol in the library Example The following example defines a function for the onMouseUp method that writes the results of a trace method to the log f...

Page 607: ...d to the log file my_mc onPress function trace onPress called MovieClip onRelease Availability Flash Player 6 Usage my_mc onRelease function your statements here Parameters None Returns Nothing Description Event handler invoked when the mouse button is released over a movie clip You must define a function that executes when the event handler is invoked You can define the function on the Timeline o...

Page 608: ...st define a function that executes when the event handler is invoked You can define the function on the Timeline or in a class file that extends the MovieClip class or is linked to a symbol in the library Example The following example defines a function for the onReleaseOutside method that writes the results of a trace method to the log file my_mc onReleaseOutside function trace onReleaseOutside c...

Page 609: ...y_mc onRollOut function trace onRollOut called MovieClip onRollOver Availability Flash Player 6 Usage my_mc onRollOver function your statements here Parameters None Returns Nothing Description Event handler invoked when the pointer moves over a movie clip area You must define a function that executes when the event handler is invoked You can define the function on the Timeline or in a class file t...

Page 610: ...ldFocus contains a null value You must define a function that executes when the event handler in invoked You can define the function on the Timeline or in a class file that extends the MovieClip class or is linked to a symbol in the library Example The following example writes information about the movie clip that receives keyboard focus and the instance that previously had focus Two movie clips c...

Page 611: ... linked to a symbol in the library Example The following example defines a function for the MovieClip onUnload method that writes the results of a trace method to the log file my_mc onUnload function trace onUnload called MovieClip _parent Availability Flash Player 5 Usage my_mc _parent property _parent property Description Property a reference to the movie clip or object that contains the current...

Page 612: ...t targetPath TextField _parent MovieClip play Availability Flash Player 5 Usage my_mc play Void Parameters None Returns Nothing Description Method moves the playhead in the Timeline of the movie clip You can extend the methods and event handlers of the MovieClip class by creating a subclass Example Use the following ActionScript to play the main Timeline of a SWF file This ActionScript is for a mo...

Page 613: ... Example In the following example two movie clip buttons control the Timeline The prev_mc button moves the playhead to the previous frame and the next_mc button moves the playhead to the next frame stop prev_mc onRelease function var parent_mc MovieClip this _parent if parent_mc _currentframe 1 parent_mc prevFrame else parent_mc gotoAndStop parent_mc _totalframes next_mc onRelease function var par...

Page 614: ...k a button in the following example you attach a movie clip instance to the Stage in a random position When you click a movie clip instance you remove that instance from the SWF file function randRange min Number max Number Number var randNum Number Math round Math random max min min return randNum var bugNum Number 0 addBug_btn onRelease addBug function addBug var thisBug MovieClip this _parent a...

Page 615: ...name of a movie clip to be masked mask_mc The instance name of a movie clip to be a mask Returns Nothing Description Method makes the movie clip in the parameter mask_mc a mask that reveals the movie clip specified by the my_mc parameter This method allows multiple frame movie clips with complex multilayered content to act as masks You can shut masks on and off at runtime However you can t use the...

Page 616: ...user first clicked on the movie clip false This parameter is optional left top right bottom Values relative to the coordinates of the movie clip s parent that specify a constraint rectangle for the movie clip These parameters are optional Returns Nothing Description Method lets the user drag the specified movie clip The movie clip remains draggable until explicitly stopped through a call to MovieC...

Page 617: ...p stopDrag MovieClip stop Availability Flash Player 5 Usage my_mc stop Void Parameters None Returns Nothing Description Method stops the movie clip currently playing You can extend the methods and event handlers of the MovieClip class by creating a subclass Example The following example shows how to stop a movie clip named aMovieClip aMovieClip stop See also stop MovieClip stopDrag Availability Fl...

Page 618: ...ject new Object mclListener onLoadInit function target_mc MovieClip target_mc onPress function this startDrag target_mc onRelease function this stopDrag var image_mcl MovieClipLoader new MovieClipLoader image_mcl addListener mclListener image_mcl loadClip http www macromedia com devnet mx blueprint articles nielsen spotlight_jnielsen jpg image_mc See also MovieClip _droptarget MovieClip startDrag ...

Page 619: ...AS or FLA file myMC1_mc onRelease function this swapDepths myMC2_mc myMC2_mc onRelease function this swapDepths myMC1_mc See also MovieClip getDepth MovieClip getInstanceAtDepth MovieClip getNextHighestDepth MovieClip tabChildren Availability Flash Player 6 Usage my_mc tabChildren Boolean Description Property undefined by default If tabChildren is undefined or true the children of a movie clip are...

Page 620: ...d in automatic tab ordering It is undefined by default If tabEnabled is undefined the object is included in automatic tab ordering only if it defines at least one movie clip handler such as MovieClip onRelease If tabEnabled is true the object is included in automatic tab ordering If the tabIndex property is also set to a value the object is included in custom tab ordering as well If tabEnabled is ...

Page 621: ...edes an object with a tabIndex value of 2 The custom tab ordering disregards the hierarchical relationships of objects in a SWF file All objects in the SWF file with tabIndex properties are placed in the tab order You shouldn t use the same tabIndex value for multiple objects Example The following ActionScript sets a custom tab order for three movie clip instances myMC1_mc onRelease function myMC2...

Page 622: ...llowing example two movie clip buttons control the Timeline The prev_mc button moves the playhead to the previous frame and the next_mc button moves the playhead to the next frame stop prev_mc onRelease function var parent_mc MovieClip this _parent if parent_mc _currentframe 1 parent_mc prevFrame else parent_mc gotoAndStop parent_mc _totalframes next_mc onRelease function var parent_mc MovieClip t...

Page 623: ...lick a movie clip and release the mouse button on a second movie clip to see which instance receives the event myMC1_mc trackAsMenu true myMC2_mc trackAsMenu true myMC3_mc trackAsMenu false myMC1_mc onRelease clickMC myMC2_mc onRelease clickMC myMC3_mc onRelease clickMC function clickMC trace you clicked the this _name movie clip MovieClip unloadMovie Availability Flash Player 5 Usage my_mc unload...

Page 624: ...o the image_mc instance to the log file this createEmptyMovieClip image_mc 1 var mclListener Object new Object mclListener onLoadInit function target_mc MovieClip trace _url target_mc _url var image_mcl MovieClipLoader new MovieClipLoader image_mcl addListener mclListener image_mcl loadClip http www macromedia com images shared product_boxes 112x112 box_studio_112x112 jpg image_mc The following ex...

Page 625: ...or is true If useHandCursor is set to true the pointing hand used for buttons is displayed when the mouse rolls over a button movie clip If useHandCursor is false the arrow pointer is used instead You can change the useHandCursor property at any time the modified movie clip immediately takes on the new cursor behavior The useHandCursor property can be read out of a prototype object Example The fol...

Page 626: ..._visible false this _visible false myMC2_mc onRelease function trace this _name _alpha 0 this _alpha 0 See also TextField _visible MovieClip _width Availability Flash Player 4 as a read only property Usage my_mc _width Number Description Property the width of the movie clip in pixels Example The following code example writes the height and width of a movie clip to the log file this createEmptyMovi...

Page 627: ...e clip s coordinates refer to the registration point position Example The following example attaches a movie clip with the linkage identifier cursor_id to a SWF file The movie clip is called cursor_mc and it is used to replace the default mouse pointer The following ActionScript sets the current coordinates of the movie clip instance to the position of the mouse pointer this attachMovie cursor_id ...

Page 628: ...roperty determines the horizontal scale percentage of the movie clip as applied from the registration point of the movie clip The default registration point is 0 0 Scaling the local coordinate system affects the _x and _y property settings which are defined in whole pixels For example if the parent movie clip is scaled to 50 setting the _x property moves an object in the movie clip by half the num...

Page 629: ...formations the movie clip is in the local coordinate system of the enclosing movie clip Thus for a movie clip rotated 90º counterclockwise the movie clip s children inherit a coordinate system that is rotated 90º counterclockwise The movie clip s coordinates refer to the registration point position Example The following example attaches a movie clip with the linkage identifier cursor_id to a SWF f...

Page 630: ...e function mouse_txt htmlText textformat tabStops 50 100 mouse_txt htmlText row1_str mouse_txt htmlText b _level0 b t _xmouse t _ymouse mouse_txt htmlText b my_mc b t this _xmouse t this _ymouse mouse_txt htmlText textformat See also Mouse class MovieClip _xmouse MovieClip _yscale Availability Flash Player 4 Usage my_mc _yscale Number Description Property sets the vertical scale percentage of the ...

Page 631: ...returns to the previous scaling this createEmptyMovieClip box_mc 1 box_mc _x 100 box_mc _y 100 with box_mc lineStyle 1 0xCCCCCC beginFill 0xEEEEEE moveTo 0 0 lineTo 80 0 lineTo 80 60 lineTo 0 60 lineTo 0 0 endFill box_mc onRollOver function this _x this _width 2 this _y this _height 2 this _xscale 200 this _yscale 200 box_mc onRollOut function this _xscale 100 this _yscale 100 this _x this _width ...

Page 632: ...r onLoadComplete listener is invoked After the downloaded file s first frame actions have been executed the MovieClipLoader onLoadInit listener is invoked After MovieClipLoader onLoadInit has been invoked you can set properties use methods and otherwise interact with the loaded movie If the file fails to load completely the MovieClipLoader onLoadError listener is invoked Method summary for the Mov...

Page 633: ...tener MovieClipLoader addListener Availability Flash Player 7 Usage my_mcl addListener listenerObject Object Void Listener Description MovieClipLoader onLoadComplete Invoked when a file loaded with MovieClipLoader loadClip has completely downloaded MovieClipLoader onLoadError Invoked when a file loaded with MovieClipLoader loadClip has failed to load MovieClipLoader onLoadInit Invoked when the act...

Page 634: ... width 2 target_mc _width 2 target_mc _y Stage height 2 target_mc _width 2 var w Number target_mc _width var h Number target_mc _height target_mc lineStyle 4 0x000000 target_mc moveTo 0 0 target_mc lineTo w 0 target_mc lineTo w h target_mc lineTo 0 h target_mc lineTo 0 0 target_mc _rotation 3 var image_mcl MovieClipLoader new MovieClipLoader image_mcl addListener mclListener image_mcl loadClip htt...

Page 635: ...t mclListener onLoadInit function target_mc MovieClip target_mc onPress function this startDrag target_mc onRelease function this stopDrag var mclProgress Object image_mcl getProgress target_mc target_mc createTextField filesize_txt target_mc getNextHighestDepth 0 target_mc _height target_mc _width 22 target_mc filesize_txt text mclProgress bytesLoaded of mclProgress bytesTotal bytes loaded var im...

Page 636: ...me of the clip have executed so you can begin manipulating the loaded clip The MovieClipLoader onLoadComplete handler is invoked when a file has completed downloading A SWF file or image loaded into a movie clip inherits the position rotation and scale properties of the movie clip You can use the target path of the movie clip to target the loaded movie You can use the loadClip method to load one o...

Page 637: ...ener onLoadInit function target_mc MovieClip trace First my_mcl instance trace Movie clip target_mc is now initialized you can now do any setup required for example target_mc _width 100 target_mc _height 100 myListener onLoadError function target_mc MovieClip errorCode String trace First my_mcl instance trace ERROR CODE errorCode trace Your load failed on movie clip target_mc n my_mcl addListener ...

Page 638: ...p target_mc n another_mcl addListener myListener2 Now load the files into their targets using the second instance of MovieClipLoader another_mcl loadClip http www macromedia com devnet images 160x160 flex_logo jpg this createEmptyMovieClip clip4_mc this getNextHighestDepth clip4_mc _y 200 Issue the following statements after the download is complete and after my_mcl onLoadInit has been called my_m...

Page 639: ...lized Example The following example loads an image into a movie clip instance called image_mc The onLoadInit and onLoadComplete events are used to determine how long it takes to load the image The information displays in a dynamically created text field called timer_txt this createEmptyMovieClip image_mc this getNextHighestDepth var mclListener Object new Object mclListener onLoadStart function ta...

Page 640: ... download is interrupted due to server overload server crash and so on MovieClipLoader onLoadComplete will not be called The value for target_mc identifies the movie clip this call is being made for This is useful if you are loading multiple files with the same set of listeners This optional parameter is passed to your ActionScript Example The following example writes information to the log file w...

Page 641: ...clip this call is being made for This is useful if you are loading multiple files with the same set of listeners This optional parameter is passed to your ActionScript Example The following example loads an image into a movie clip instance called image_mc The onLoadInit and onLoadComplete events are used to determine how long it takes to load the image This information displays in a text field cal...

Page 642: ...ip loaded by a MovieClipLoader loadClip method This parameter is optional loadedBytes The number of bytes that had been loaded when the listener was invoked totalBytes The total number of bytes in the file being loaded Returns Nothing Description Listener invoked every time the loading content is written to disk during the loading process that is between MovieClipLoader onLoadStart and MovieClipLo...

Page 643: ...teEmptyMovieClip stroke_mc 2 with progressBar_mc stroke_mc lineStyle 0 0x000000 moveTo 0 0 lineTo 100 0 lineTo 100 10 lineTo 0 10 lineTo 0 0 with progressBar_mc bar_mc beginFill 0xFF0000 100 moveTo 0 0 lineTo 100 0 lineTo 100 10 lineTo 0 10 lineTo 0 0 endFill _xscale 0 progressBar_mc _x 2 progressBar_mc _y 2 var mclListener Object new Object mclListener onLoadStart function target_mc MovieClip pro...

Page 644: ...ing example loads an image into a movie clip instance called image_mc The onLoadInit and onLoadComplete events are used to determine how long it takes to load the image This information displays in a text field called timer_txt this createEmptyMovieClip image_mc this getNextHighestDepth var mclListener Object new Object mclListener onLoadStart function target_mc MovieClip target_mc startTimer getT...

Page 645: ...t and stop the loading process using two buttons called start_button and stop_button When the user starts or stops the progress information writes to the log file this createEmptyMovieClip image_mc this getNextHighestDepth var mclListener Object new Object mclListener onLoadStart function target_mc MovieClip trace t onLoadStart mclListener onLoadComplete function target_mc MovieClip trace t onLoad...

Page 646: ...If you issue this command while a movie is loading MovieClipLoader onLoadError is invoked Example The following example loads an image into a movie clip called image_mc If you click the movie clip the movie clip is removed and information writes to the log file this createEmptyMovieClip image_mc this getNextHighestDepth var mclListener Object new Object mclListener onLoadInit function target_mc Mo...

Page 647: ...on Usage new NetConnection NetConnection Parameters None Returns A reference to a NetConnection object Description Constructor creates a NetConnection object that you can use in conjunction with a NetStream object to play back local streaming video FLV files After creating the NetConnection object use NetConnection connect to make the actual connection Playing external FLV files provides several a...

Page 648: ...Constructor opens a local connection through which you can play back video FLV files from an HTTP address or from the local file system Example The following example opens a connection to play the video2 flv file Select New Video from the Library panel s options menu to create a new video object and give it the instance name my_video var connection_nc NetConnection new NetConnection connection_nc ...

Page 649: ...The following methods and properties of the NetConnection and NetStream classes are used to control FLV playback Property summary for the NetStream class Method Purpose NetStream close Closes the stream but does not clear the video object NetStream pause Pauses or resumes playback of a stream NetStream play Begins playback of an external video FLV file NetStream seek Seeks a specific position in t...

Page 650: ...tructs a new NetConnection object connection_nc and uses it to construct a new NetStream object called stream_ns Create a new video object called my_video Then add the following ActionScript to your FLA or AS file var connection_nc NetConnection new NetConnection connection_nc connect null var stream_ns NetStream new NetStream connection_nc my_video attachVideo stream_ns stream_ns play video1 flv ...

Page 651: ...ffer_txt html true var connection_nc NetConnection new NetConnection connection_nc connect null var stream_ns NetStream new NetStream connection_nc stream_ns setBufferTime 3 my_video attachVideo stream_ns stream_ns play video1 flv var buffer_interval Number setInterval checkBufferTime 100 stream_ns function checkBufferTime my_ns NetStream Void var bufferPct Number Math min Math round my_ns bufferL...

Page 652: ... NetStream new NetStream connection_nc stream_ns setBufferTime 3 my_video attachVideo stream_ns stream_ns play video1 flv var buffer_interval Number setInterval checkBufferTime 100 stream_ns function checkBufferTime my_ns NetStream Void var bufferPct Number Math min Math round my_ns bufferLength my_ns bufferTime 100 100 var output_str String textformat tabStops 100 200 output_str Length my_ns buff...

Page 653: ...ogressBar_mc this getNextHighestDepth progressBar_mc createEmptyMovieClip bar_mc progressBar_mc getNextHighestDepth with progressBar_mc bar_mc beginFill 0xFF0000 moveTo 0 0 lineTo 100 0 lineTo 100 10 lineTo 0 10 lineTo 0 0 endFill _xscale 0 progressBar_mc createEmptyMovieClip stroke_mc progressBar_mc getNextHighestDepth with progressBar_mc stroke_mc lineStyle 0 0x000000 moveTo 0 0 lineTo 100 0 lin...

Page 654: ...r stream_ns NetStream new NetStream connection_nc my_video attachVideo stream_ns stream_ns play video1 flv this createTextField loaded_txt this getNextHighestDepth 10 10 160 22 this createEmptyMovieClip progressBar_mc this getNextHighestDepth progressBar_mc createEmptyMovieClip bar_mc progressBar_mc getNextHighestDepth with progressBar_mc bar_mc beginFill 0xFF0000 moveTo 0 0 lineTo 100 0 lineTo 10...

Page 655: ...s None Returns Nothing Description Method stops playing all data on the stream sets the NetStream time property to 0 and makes the stream available for another use This command also deletes the local copy of an FLV file that was downloaded using HTTP Example The following onDisconnect function closes a connection and deletes the temporary copy of video1 flv that was stored on the local disk when y...

Page 656: ...splays var connection_nc NetConnection new NetConnection connection_nc connect null var stream_ns NetStream new NetStream connection_nc my_video attachVideo stream_ns stream_ns play video1 flv this createTextField fps_txt this getNextHighestDepth 10 10 50 22 fps_txt autoSize true var fps_interval Number setInterval displayFPS 500 stream_ns function displayFPS my_ns NetStream fps_txt text currentFp...

Page 657: ...ld try changing the buffer using the NetStream setBufferTime method Example The following example writes data about the stream to the log file var connection_nc NetConnection new NetConnection connection_nc connect null var stream_ns NetStream new NetStream connection_nc my_video attachVideo stream_ns stream_ns play video1 flv stream_ns onStatus function infoObject Object trace NetStream onStatus ...

Page 658: ...umes play This parameter is optional Returns Nothing Description Method pauses or resumes playback of a stream The first time you call this method without sending a parameter it pauses play the next time it resumes play You might want to attach this method to a button that the user presses to pause or resume playback Example The following examples illustrate some uses of this method my_ns pause pa...

Page 659: ...want to stop a stream that is currently playing use NetStream close You can play local FLV files that are stored in the same directory as the SWF file or in a subdirectory you can t navigate to a higher level directory For example if the SWF file is located in a directory named training and you want to play a video stored in the training videos directory you would use the following syntax my_ns pl...

Page 660: ...n to seek n seconds forward or backward respectively from the current position For example to rewind 20 seconds from the current position use my_ns seek my_ns time 20 The precise location to which a video seeks will differ depending on the frames per second setting at which it was exported Therefore if the same video is exported at 6 fps and 30 fps it will seek to two different locations if you us...

Page 661: ...econds to 15 Flash begins playing the stream only after 15 seconds of data are buffered Example See the example for NetStream bufferLength See also NetStream bufferTime NetStream time Availability Flash Player 7 Note This property is also supported in Flash Player 6 when used with Flash Communication Server For more information see the Flash Communication Server documentation Usage my_ns time Numb...

Page 662: ... getNextHighestDepth 10 10 100 22 time_txt text LOADING var time_interval Number setInterval checkTime 500 stream_ns function checkTime my_ns NetStream var ns_seconds Number my_ns time var minutes Number Math floor ns_seconds 60 var seconds Math floor ns_seconds 60 if seconds 10 seconds 0 seconds time_txt text minutes seconds See also NetStream bufferLength NetStream bytesLoaded ...

Page 663: ...ons that are attached to the affected frames mouseMove The action is initiated every time the mouse is moved Use the _xmouse and _ymouse properties to determine the current mouse position mouseDown The action is initiated when the left mouse button is pressed mouseUp The action is initiated when the left mouse button is released keyDown The action is initiated when a key is pressed Use Key getCode...

Page 664: ...perty the playhead is sent to the previous frame onClipEvent keyDown if Key getCode Key RIGHT this _parent nextFrame else if Key getCode Key LEFT this _parent prevFrame The following example uses onClipEvent with the load and mouseMove movie events The _xmouse and _ymouse properties track the position of the mouse each time the mouse moves which appears in the text field that s created at runtime ...

Page 665: ...ector onUpdate is invoked The onUpdate function does something to update itself For instance if the component includes a color parameter the onUpdate function might alter the color of a movie clip inside the Live Preview to reflect the new parameter value In addition it might store the new color in an internal variable The following example uses the onUpdate function to pass parameter values throu...

Page 666: ...ve the current movie clip or object Example In the following example there is a movie clip on the Stage with the instance name square_mc Within that movie clip is another movie clip with an instance name circle_mc The following ActionScript lets you modify the circle_mc parent instance which is square_mc when the circle is clicked When you are working with relative addressing using _parent instead...

Page 667: ...alled newClip_mc Images are loaded into both movie clips When a button button_mc is clicked the duplicated movie clip is removed from the Stage this createEmptyMovieClip myClip_mc this getNextHighestDepth myClip_mc loadMovie http www macromedia com devnet mx blueprint articles server_side jeremy_gray jpg duplicateMovieClip this myClip_mc newClip_mc this getNextHighestDepth newClip_mc loadMovie htt...

Page 668: ...oot is the same as using the deprecated slash notation to specify an absolute path within the current level Caution If a movie clip that contains _root is loaded into another movie clip _root refers to the Timeline of the loading movie clip not the Timeline that contains _root If you want to ensure that _root refers to the Timeline of the loaded movie clip even if it is loaded into another movie c...

Page 669: ...tBeginIndex Returns the index at the beginning of the selection span Returns 1 if there is no index or currently selected field Selection getCaretIndex Returns the current caret insertion point position in the currently focused selection span Returns 1 if there is no caret position or currently focused selection span Selection getEndIndex Returns the index at the end of the selection span Returns ...

Page 670: ...ssigns a function The function takes two parameters a reference to the text field that lost focus and one to the text field that gained focus The function sets the border property of the text field that lost focus to false and sets the border property of the text field that gained focus to true this createTextField one_txt 99 10 10 200 20 this createTextField two_txt 100 10 50 200 20 one_txt borde...

Page 671: ...d output_txt this getNextHighestDepth 0 0 300 200 output_txt multiline true output_txt wordWrap true output_txt border true output_txt type input output_txt text Enter your text here var my_cm ContextMenu new ContextMenu my_cm customItems push new ContextMenuItem Uppercase doUppercase function doUppercase Void var startIndex Number Selection getBeginIndex var endIndex Number Selection getEndIndex ...

Page 672: ...hestDepth 50 50 400 300 content_txt border true content_txt type input content_txt wordWrap true content_txt multiline true content_txt onChanged getCaretPos var keyListener Object new Object keyListener onKeyUp getCaretPos Key addListener keyListener var mouseListener Object new Object mouseListener onMouseUp getCaretPos Mouse addListener mouseListener function getCaretPos pos_txt text Selection ...

Page 673: ...context menu item convert the selected text to upper case tempString target text substring beginIndex endIndex toUpperCase break case Lowercase tempString target text substring beginIndex endIndex toLowerCase break append the text after the selected text to the temporary string tempString target text slice endIndex set the text in the target text field to the contents of the temporary string targe...

Page 674: ...ols TextArea my_mc onRelease function my_btn onRelease function var keyListener Object new Object keyListener onKeyDown function if Key isDown Key SPACE focus_ta text Selection getFocus newline focus_ta text Key addListener keyListener Test the SWF file and use Tab to move between the instances on the Stage See also Selection onSetFocus Selection setFocus Selection onSetFocus Availability Flash Pl...

Page 675: ... i in this if this i instanceof TextField this i border true this i type input this createTextField status_txt this getNextHighestDepth 200 10 300 100 status_txt html true status_txt multiline true var someListener Object new Object someListener onSetFocus function oldFocus newFocus status_txt htmlText b setFocus triggered b status_txt htmlText textformat tabStops 20 80 status_txt htmlText nbsp to...

Page 676: ...t 2 0 25 100 22 this createTextField three_txt 3 0 50 100 22 this createTextField four_txt 4 0 75 100 22 for var i in this if this i instanceof TextField this i border true this i type input var selectionListener Object new Object selectionListener onSetFocus function oldFocus newFocus trace Focus shifted from oldFocus to newFocus Selection addListener selectionListener remove_btn onRelease functi...

Page 677: ... automatically focuses in the text field that s missing data For example if the user does not type anything into the username_txt text field and clicks the submit button an error message appears and the cursor focuses in the username_txt text field this createTextField status_txt this getNextHighestDepth 100 70 100 22 this createTextField username_txt this getNextHighestDepth 100 100 100 22 this c...

Page 678: ...text field The new selection span will begin at the index specified in the start parameter and end at the index specified in the end parameter Selection span indexes are zero based for example the first position is 0 the second position is 1 and so on This method has no effect if there is no currently focused text field Example In the following ActionScript you create a text field at runtime and a...

Page 679: ...ip as the movie clip plays Example The following ActionScript creates a new movie clip and loads an image into it The _x and _y coordinates are set for the clip using setProperty When you click the button called right_btn the _x coordinate of a movie clip named params_mc is incremented by 20 pixels this createEmptyMovieClip params_mc 999 params_mc loadMovie http www macromedia com devnet mx bluepr...

Page 680: ...Returns the size of the sound in bytes Sound getPan Returns the value of the previous setPan call Sound getTransform Returns the value of the previous setTransform call Sound getVolume Returns the value of the previous setVolume call Sound loadSound Loads an MP3 file into Flash Player Sound setPan Sets the left right balance of the sound Sound setTransform Sets the amount of each channel left and ...

Page 681: ...he following example creates a new Sound object called global_sound The second line calls setVolume and adjusts the volume on all sounds in the movie to 50 var global_sound Sound new Sound global_sound setVolume 50 The following example creates a new Sound object passes it the target movie clip my_mc and calls the start method which starts any sound in my_mc var movie_sound Sound new Sound my_mc m...

Page 682: ... has the linkage identifier logoff_id var my_sound Sound new Sound my_sound attachSound logoff_id my_sound start Sound duration Availability Flash Player 6 Usage my_sound duration Number Description Read only property the duration of a sound in milliseconds Example The following example loads a sound and writes the duration of the sound file to the log file Add the following ActionScript to your F...

Page 683: ... stroke_mc pb getNextHighestDepth pb createTextField pos_txt pb getNextHighestDepth 0 pb_height pb_width 22 pb _x 100 pb _y 100 with pb bar_mc beginFill 0x00FF00 moveTo 0 0 lineTo pb_width 0 lineTo pb_width pb_height lineTo 0 pb_height lineTo 0 0 endFill _xscale 0 with pb vBar_mc lineStyle 1 0x000000 moveTo 0 0 lineTo 0 pb_height with pb stroke_mc lineStyle 3 0x000000 moveTo 0 0 lineTo pb_width 0 ...

Page 684: ...esTotal to determine what percentage of a sound has loaded Example The following example dynamically creates two text fields that display the bytes that are loaded and the total number of bytes for a sound file that loads into the SWF file A text field also displays a message when the file finishes loading Add the following ActionScript to your FLA or AS file this createTextField message_txt this ...

Page 685: ...d of the_sound getBytesTotal bytes pct newline status_txt text the_sound position of the_sound duration milliseconds pos newline See also Sound getBytesTotal Sound getBytesTotal Availability Flash Player 6 Usage my_sound getBytesTotal Number Parameters None Returns An integer indicating the total size in bytes of the specified Sound object Description Method returns the size in bytes of the specif...

Page 686: ...ly created text field Add the following ActionScript to your FLA or AS file var bar_width Number 200 this createEmptyMovieClip bar_mc this getNextHighestDepth with bar_mc lineStyle 4 0x000000 moveTo 0 0 lineTo bar_width 4 0 lineStyle 0 0x000000 moveTo bar_width 2 2 8 lineTo bar_width 2 2 8 bar_mc _x 100 bar_mc _y 100 this createEmptyMovieClip knob_mc this getNextHighestDepth with knob_mc lineStyle...

Page 687: ... object with properties that contain the channel percentage values for the specified sound object Description Method returns the sound transform information for the specified Sound object set with the last Sound setTransform call Example The following example attaches four movie clips from a symbol in the library linkage identifier knob_id that are used as sliders or knobs to control the sound fil...

Page 688: ...form_obj ll knob_ll onPress pressKnob knob_ll onRelease releaseKnob knob_ll onReleaseOutside releaseKnob knob_lr top knob_lr _y knob_lr bottom knob_lr _y 100 knob_lr left knob_lr _x knob_lr right knob_lr _x knob_lr _y knob_lr _y 100 transform_obj lr knob_lr onPress pressKnob knob_lr onRelease releaseKnob knob_lr onReleaseOutside releaseKnob knob_rl top knob_rl _y knob_rl bottom knob_rl _y 100 knob...

Page 689: ...ound getVolume Availability Flash Player 5 Usage my_sound getVolume Number Parameters None Returns An integer Description Method returns the sound volume level as an integer from 0 to 100 where 0 is off and 100 is full volume The default setting is 100 Example The following example creates a slider using the Drawing API and a movie clip that is created at runtime A dynamically created text field d...

Page 690: ...g true knob_mc onMouseMove function if this isDragging this volume_txt text this _x knob_mc onRelease function this stopDrag this isDragging false my_sound setVolume this _x See also Sound setVolume Sound id3 Availability Flash Player 6 behavior updated in Flash Player 7 Usage my_sound id3 Object Description Read only property provides access to the metadata that is part of an MP3 file MP3 sound f...

Page 691: ...Album movie show title TBPM Beats per minute TCOM Composer TCON Content type TCOP Copyright message TDAT Date TDLY Playlist delay TENC Encoded by TEXT Lyricist text writer TFLT File type TIME Time TIT1 Content group description TIT2 Title song name content description TIT3 Subtitle description refinement TKEY Initial key TLAN Languages TLEN Length TMED Media type TOAL Original album movie show tit...

Page 692: ..._sound Sound new Sound my_sound onID3 function for var prop in my_sound id3 trace prop my_sound id3 prop my_sound loadSound song mp3 false See also Sound attachSound Sound loadSound TPOS Part of a set TPUB Publisher TRCK Track number position in set TRDA Recording dates TRSN Internet radio station name TRSO Internet radio station owner TSIZ Size TSRC ISRC international standard recording code TSSE...

Page 693: ...ounds are completely loaded before they play They are managed by the ActionScript Sound class and respond to all methods and properties of this class Streaming sounds play while they are downloading Playback begins when sufficient data has been received to start the decompressor All MP3s event or streaming loaded with this method are saved in the browser s file cache on the user s system Example T...

Page 694: ...ith the instance name id3_dg to your document and add the following ActionScript to your FLA or AS file import mx controls gridclasses DataGridColumn var id3_dg mx controls DataGrid id3_dg move 0 0 id3_dg setSize Stage width Stage height var property_dgc DataGridColumn id3_dg addColumn new DataGridColumn property property_dgc width 100 property_dgc headerText ID3 Property var value_dgc DataGridCol...

Page 695: ...ample The following example creates a new Sound object and loads a sound Loading the sound is handled by the onLoad handler which allows you to start the song after it is successfully loaded Create a new FLA file and add the following ActionScript to your FLA or AS file For this example to work you must have an MP3 called song1 mp3 in the same directory as your FLA or AS file this createTextField ...

Page 696: ...st create a function that executes when this handler is invoked You can use either an anonymous function or a named function Example Usage 1 The following example uses an anonymous function var my_sound Sound new Sound my_sound attachSound mySoundID my_sound onSoundComplete function trace mySoundID completed my_sound start Usage 2 The following example uses a named function function callback1 trac...

Page 697: ...Pan pan Number Number Parameters pan An integer specifying the left right balance for a sound The range of valid values is 100 to 100 where 100 uses only the left channel 100 uses only the right channel and 0 balances the sound evenly between the two channels Returns An integer Description Method determines how the sound is played in the left and right channels speakers For mono sounds pan determi...

Page 698: ...rm to play mono sounds as stereo play stereo sounds as mono and to add interesting effects to sounds The properties for the soundTransformObject are as follows 11 A percentage value specifying how much of the left input to play in the left speaker 0 100 1r A percentage value specifying how much of the right input to play in the left speaker 0 100 rr A percentage value specifying how much of the ri...

Page 699: ...ransform as follows my_sound setTransform mySoundTransformObject The following example plays a stereo sound as mono the soundTransformObjectMono object has the following parameters var mySoundTransformObjectMono Object new Object mySoundTransformObjectMono ll 50 mySoundTransformObjectMono lr 50 mySoundTransformObjectMono rr 50 mySoundTransformObjectMono rl 50 my_sound setTransform mySoundTransform...

Page 700: ...e my_sound start secondOffset Number loop Number Void Parameters secondOffset An optional parameter that lets you start playing the sound at a specific point For example if you have a 30 second sound and want the sound to start playing in the middle specify 15 for the secondOffset parameter The sound is not delayed 15 seconds but rather starts playing at the 15 second mark loop An optional paramet...

Page 701: ...stDepth 0 0 100 22 create a new Sound object var my_sound Sound new Sound if the sound loads play it if not trace failure loading my_sound onLoad function success Boolean if success my_sound start status_txt text Sound loaded else status_txt text Sound failed load the sound my_sound loadSound song1 mp3 true See also Sound stop Sound stop Availability Flash Player 5 Usage my_sound stop idName Strin...

Page 702: ...a sound that loads into a SWF file Add two buttons to your document and add the following ActionScript to your FLA or AS file var my_sound Sound new Sound my_sound loadSound song1 mp3 true stop_btn onRelease function trace sound stopped my_sound stop play_btn onRelease function trace sound started my_sound start See also Sound start ...

Page 703: ...er the MP3 for 10 seconds A new Sound object instance is created for the MP3 create text fields to hold debug information this createTextField counter_txt this getNextHighestDepth 0 0 100 22 this createTextField debug_txt this getNextHighestDepth 0 20 100 22 set the sound buffer to 10 seconds _soundbuftime 10 create the new sound object instance var bg_sound Sound new Sound load the MP3 sound file...

Page 704: ...e addListener myListener Object Void Parameters myListener An object that listens for a callback notification from the Stage onResize event Method Description Stage addListener Adds a listener object that detects when a SWF file is resized Stage removeListener Removes a listener object from the Stage object Property Description Stage align Alignment of the SWF file in the player or browser Stage h...

Page 705: ...he callback list of the Stage object Listener objects allow multiple objects to listen for resize notifications this createTextField stageSize_txt this getNextHighestDepth 10 10 100 22 var stageListener Object new Object stageListener onResize function stageSize_txt text w Stage width h Stage height Stage scaleMode noScale Stage addListener stageListener See also Stage onResize Stage removeListene...

Page 706: ...erty read only indicates the current height in pixels of the Stage When the value of Stage scaleMode is noScale the height property represents the height of Flash Player When the value of Stage scaleMode is not noScale height represents the height of the SWF file Example This example creates a new listener object called stageListener It then uses myListener to call onResize and define a function t...

Page 707: ...is event handler to write a function that lays out the objects on the Stage when a SWF file is resized Example The following example writes the results of the trace method to the log file when the Stage is resized Stage scaleMode noScale var myListener Object new Object myListener onResize function trace Stage size is now Stage width by Stage height Stage addListener myListener later call Stage re...

Page 708: ...ttings dialog box The scaleMode property can use the values exactFit showAll noBorder and noScale Any other value sets the scaleMode property to the default showAll Example The following example demonstrates various scale settings for the SWF file Add a ComboBox instance to your document with the instance name scaleMode_cb Add the following ActionScript to your FLA or AS file var scaleMode_cb mx c...

Page 709: ...tage width Availability Flash Player 6 Usage Stage width Number Description Property read only indicates the current width in pixels of the Stage When the value of Stage scaleMode is noScale the width property represents the width of Flash Player This means that Stage width will vary as you resize the player window When the value of Stage scaleMode is not noScale width represents the width of the ...

Page 710: ...r 7 ActionScript for Flash stageListener onResize function stageSize_txt text w Stage width h Stage height Stage scaleMode noScale Stage addListener stageListener See also Stage align Stage height Stage scaleMode ...

Page 711: ...gged at a time After a startDrag operation is executed the movie clip remains draggable until it is explicitly stopped by stopDrag or until a startDrag action for another movie clip is called Example The following example creates a movie clip pic_mc at runtime that users can drag to any location by attaching the startDrag and stopDrag actions to the movie clip An image is loaded into pic_mc using ...

Page 712: ... Flash 2 Usage stop Parameters None Returns Nothing Description Function stops the SWF file that is currently playing The most common use of this action is to control movie clips with buttons See also MovieClip gotoAndStop CHAPTER 7 ActionScript for Flash ...

Page 713: ...he sound is paused When the user clicks play_mc the song resumes from its paused position this createTextField songinfo_txt this getNextHighestDepth 0 0 Stage width 22 var bg_sound Sound new Sound bg_sound loadSound yourSong mp3 true bg_sound onID3 function songinfo_txt text this id3 artist this id3 album this id3 track this id3 songname for prop in this id3 trace prop this id3 prop trace ID3 load...

Page 714: ... stops the current drag operation Example The following code placed in the main Timeline stops the drag action on the movie clip instance my_mc when the user releases the mouse button my_mc onPress function startDrag this my_mc onRelease function stopDrag See also MovieClip _droptarget MovieClip stopDrag startDrag CHAPTER 7 ActionScript for Flash ...

Page 715: ...h of the specified movie clip Description Function returns a string containing the target path of movieClipObject The target path is returned in dot notation To retrieve the target path in slash notation use the _target property Example The following example traces the target path of a movie clip as soon as it loads this createEmptyMovieClip myClip_mc this getNextHighestDepth trace targetPath myCl...

Page 716: ...pth Returns the depth of a text field TextField getNewTextFormat Gets the default text format assigned to newly inserted text TextField getTextFormat Returns a TextFormat object containing formatting information for some or all text in a text field TextField removeListener Removes a listener object TextField removeTextField Removes a text field that was created with MovieClip createTextField TextF...

Page 717: ...ect with a text field TextField mouseWheelEnabled Indicates whether Flash Player should automatically scroll multiline text fields when the mouse pointer is positioned over a text field and the user rolls the mouse wheel TextField multiline Indicates if the text field contains multiple lines TextField _name The instance name of a text field instance TextField _parent A reference to the instance th...

Page 718: ... the text field word wraps TextField _x The x coordinate of a text field instance TextField _xmouse Read only the x coordinate of the pointer relative to a text field instance TextField _xscale The value specifying the percentage for horizontally scaling a text field instance TextField _y The y coordinate of a text field instance TextField _ymouse Read only the y coordinate of the pointer relative...

Page 719: ...andler method For example the following code uses txt as the parameter that is passed to the onScroller event handler The parameter is then used in a trace method to write the instance name of the text field to the log file my_txt onScroller function textfield_txt TextField trace textfield_txt _name scrolled Example The following example defines an onChanged handler for the input text field my_txt...

Page 720: ...a property of a text field named my_txt to 20 Set the linkage for a font symbol to my font Add the following ActionScript to your FLA or AS file var my_fmt TextFormat new TextFormat my_fmt font my font where my font is the linkage name of a font in the Library this createTextField my_txt this getNextHighestDepth 10 10 100 22 my_txt border true my_txt embedFonts true my_txt text Hello World my_txt ...

Page 721: ...eld will be resized and the left side will remain fixed If autoSize is set to center then the text is treated as center justified text meaning any resizing of a single line text field will be equally distributed to both the right and left sides If the text includes a line break for example n or r then the bottom side will also be resized to fit the next line of text If wordWrap is also set to true...

Page 722: ...tener myMouseListener TextField background Availability Flash Player 6 Usage my_txt background Boolean Description Property if true the text field has a background fill If false the text field has no background fill Example The following example creates a text field with a background color that toggles on and off when nearly any key on the keyboard is pressed this createTextField my_txt this getNe...

Page 723: ...mple The following example creates a text field called my_txt sets the border property to true and displays some text in the field this createTextField my_txt this getNextHighestDepth 10 10 320 240 my_txt border true my_txt text Lorum ipsum TextField borderColor Availability Flash Player 6 Usage my_txt borderColor Number Description Property the color of the text field border the Default is 0x0000...

Page 724: ...e creates a text field and fills it with text The scroll and bottomScroll properties for the text field are then traced for the comment_txt field this createTextField comment_txt this getNextHighestDepth 0 0 160 120 comment_txt html true comment_txt selectable true comment_txt multiline true comment_txt wordWrap true comment_txt htmlText b What is hexadecimal b br The hexadecimal color system uses...

Page 725: ...t to your FLA or AS file var my_str String Hello tWorld nHow are you t t tEnd this createTextField first_txt this getNextHighestDepth 10 10 160 120 first_txt html true first_txt multiline true first_txt wordWrap true first_txt condenseWhite false first_txt border true first_txt htmlText my_str this createTextField second_txt this getNextHighestDepth 180 10 160 120 second_txt html true second_txt m...

Page 726: ...mat my_fmt my_txt _rotation 45 TextField getDepth Availability Flash Player 6 Usage my_txt getDepth Number Parameters None Returns An integer Description Method returns the depth of a text field Example The following example demonstrates text fields residing at different depths Add the following ActionScript to your FLA or AS file which dynamically creates two text fields at runtime and outputs th...

Page 727: ...the player s host system as an array It does not return names of all fonts in currently loaded SWF files The names are of type String Example The following code displays a font list returned by getFontList var font_array Array TextField getFontList font_array sort trace You have font_array length fonts currently installed trace for var i 0 i font_array length i trace Font i 1 t font_array i TextFi...

Page 728: ... endIndex Number Object Parameters index An integer that specifies a character in a string beginIndex endIndex Integers that specify the starting and ending locations of a span of text within my_txt Returns An object Description Method returns a TextFormat object containing a particular kind of information Usage 1 returns a TextFormat object containing formatting information for all text in a text...

Page 729: ...so TextField getNewTextFormat TextField setNewTextFormat TextField setTextFormat TextField _height Availability Flash Player 6 Usage my_txt _height Number Description Property the height of the text field in pixels Example The following code example sets the height and width of a text field my_txt _width 200 my_txt _height 200 TextField hscroll Availability Flash Player 6 Usage my_txt hscroll Numb...

Page 730: ...isplays in a text field called scroll_txt Add the following ActionScript to your FLA or AS file this createTextField scroll_txt this getNextHighestDepth 10 10 160 20 this createTextField my_txt this getNextHighestDepth 10 30 160 22 my_txt border true my_txt multiline false my_txt wordWrap false my_txt text Lorem ipsum dolor sit amet consectetuer adipiscing scrollLeft_btn onRelease function my_txt ...

Page 731: ...xt field it behaves identically to the text property You can indicate that a text field is an HTML text field in the Property inspector or by setting the text field s html property to true Example The following example creates a text field that sets the html property to true HTML formatted text displays in the text field this createTextField my_txt this getNextHighestDepth 10 10 160 22 my_txt html...

Page 732: ...tain A script may insert more text than maxChars allows the maxChars property indicates only how much text a user can enter If the value of this property is null there is no limit on the amount of text a user can enter Example The following example creates a text field called age_txt that only lets users enter up to two numbers in the field this createTextField age_txt this getNextHighestDepth 10 ...

Page 733: ...e true my_txt wordWrap true for var i 0 i 10 i my_txt text Lorem ipsum dolor sit amet consectetuer adipiscing elit sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat scrollUp_btn onRelease function my_txt scroll scroll_txt text my_txt scroll of my_txt maxscroll scrollDown_btn onRelease function my_txt scroll scroll_txt text my_txt scroll of my_txt maxscroll TextF...

Page 734: ...r menu_cm ContextMenu new ContextMenu menu_cm customItems push new ContextMenuItem Resize doResize function doResize obj TextField item ContextMenuItem Void Resize code here trace you selected item caption news_txt menu menu_cm When you right click or Control click within the area of the text field you see the custom menu item Caution You cannot use a menu item that is already used by Flash For ex...

Page 735: ...0 nonscrollable_txt border true nonscrollable_txt wordWrap true nonscrollable_txt multiline true nonscrollable_txt mouseWheelEnabled false nonscrollable_txt text font_array join n See also Mouse onMouseWheel TextField multiline Availability Flash Player 6 Usage my_txt multiline Boolean Description Property indicates whether the text field is a multiline text field If the value is true the text fie...

Page 736: ...Depth 10 10 100 22 this createTextField second_mc this getNextHighestDepth 10 10 100 22 for var prop in this if this prop instanceof TextField var this_txt TextField this prop trace this_txt _name is a TextField at depth this_txt getDepth When you test the document the instance name and depth writes to the log file TextField onChanged Availability Flash Player 6 Usage my_txt onChanged function you...

Page 737: ... in the text field using the mouse or selecting a menu item Programmatic changes to the text field do not trigger the onChanged event because the code recognizes changes that are made to the text field TextField onKillFocus Availability Flash Player 6 Usage my_txt onKillFocus function newFocus Object your statements here Parameters newFocus The object that is receiving the focus Returns Nothing De...

Page 738: ...properties changes A reference to the text field instance is passed as a parameter to the onScroller handler You can capture this data by putting a parameter in the event handler method For example the following code uses my_txt as the parameter that is passed to the onScroller event handler The parameter is then used in a trace method to write the instance name of the text field to the log file m...

Page 739: ...o buttons with instance names scrollUp_btn and scrollDown_btn and add the following ActionScript to your FLA or AS file this createTextField scroll_txt this getNextHighestDepth 10 10 160 20 this createTextField my_txt this getNextHighestDepth 10 30 320 240 my_txt multiline true my_txt wordWrap true for var i 0 i 10 i my_txt text Lorem ipsum dolor sit amet consectetuer adipiscing elit sed diam nonu...

Page 740: ...ng the ActionScript code that references _parent Use _parent to specify a relative path to movie clips or objects that are above the current text field You can use _parent to climb up multiple levels in the display list as in the following _parent _parent _alpha 20 Example The following ActionScript creates two text fields and outputs information about the _parent of each object The first text fie...

Page 741: ...rs will not function This security mechanism prevents an unscrupulous user from using the shortcuts to discover a password on an unattended computer Example The following example creates two text fields username_txt and password_txt Text is entered into both text fields however password_txt has the password property set to true Therefore the characters display as asterisks instead of as characters...

Page 742: ...ged or TextField onScroller Returns If listener was successfully removed the method returns a true value If listener was not successfully removed for example if listener was not on the TextField object s listener list the method returns a value of false Description Method removes a listener object previously registered to a text field instance with TextField addListener Example The following examp...

Page 743: ...be performed on a text field that was created with MovieClip createTextField When you call this method the text field is removed This method is similar to MovieClip removeMovieClip Example The following example creates a text field that you can remove from the Stage when you click the remove_btn instance Create a button and call it remove_btn and then add the following ActionScript to your FLA or ...

Page 744: ...field you can select Enter current date from the context menu This selection calls a function that replaces the selected text with the current date this createTextField my_txt this getNextHighestDepth 10 10 320 240 my_txt border true my_txt wordWrap true my_txt multiline true my_txt type input my_txt text Select some sample text from the text field and then right click control click and select Ent...

Page 745: ...ing Description Property indicates the set of characters that a user may enter into the text field If the value of the restrict property is null you can enter any character If the value of the restrict property is an empty string you can t enter any character If the value of the restrict property is a string of characters you can enter only characters in the string into the text field The string i...

Page 746: ...Flash Player 6 Usage my_txt _rotation Number Description Property the rotation of the text field in degrees from its original orientation Values from 0 to 180 represent clockwise rotation values from 0 to 180 represent counterclockwise rotation Values outside this range are added to or subtracted from 360 to obtain a value within the range For example the statement my_txt _rotation 450 is the same...

Page 747: ...xt in its entirety as opposed to seeing a partial line Even if there are multiple fonts on a line the height of the line adjusts to fit the largest font in use Example The following example sets the maximum value for the scrolling text field my_txt Create two buttons scrollUp_btn and scrollDown_btn to scroll the text field Add the following ActionScript to your FLA or AS file this createTextField ...

Page 748: ... and the text cannot be copied using the Copy command If selectable is set to true the text in the text field can be selected using the mouse or keyboard You can select text this way even if the text field is a dynamic text field instead of an input text field The text can be copied using the Copy command Example The following example creates a selectable text field that constantly updates with th...

Page 749: ..._fmt color 0xFF9900 this createTextField my_txt 999 0 0 400 300 my_txt wordWrap true my_txt multiline true my_txt border true my_txt type input my_txt setNewTextFormat my_fmt my_txt text Oranges are a good source of vitamin C See also TextField getNewTextFormat TextField getTextFormat TextField setTextFormat TextField setTextFormat Availability Flash Player 6 Usage my_txt setTextFormat textFormat ...

Page 750: ...ies the properties of textFormat to all text in the text field Usage 2 Applies the properties of textFormat to the character at position index Usage 3 Applies the properties of the textFormat parameter to the span of text from the beginIndex parameter to the endIndex parameter Notice that any text inserted manually by the user or replaced by means of TextField replaceSel receives the text field s ...

Page 751: ...s1_btn css2_btn and clearCss_btn are used to change the style sheet that is applied to news_txt or clear the style sheet from the text field Add the following ActionScript to your FLA or AS file this createTextField news_txt this getNextHighestDepth 0 0 300 200 news_txt wordWrap true news_txt multiline true news_txt html true var newsText String p class headline Description p Method starts loading...

Page 752: ...fined news_txt htmlText newsText The following styles are applied to the text field Save the following two CSS files in the same directory as the FLA or AS file you created previously in styles css important color FF0000 bold font weight bold headline color 000000 font family Arial Helvetica sans serif font size 18px font weight bold display block in styles2 css important color FF00FF bold font we...

Page 753: ...veral text fields called one_txt two_txt three_txt and four_txt The three_txt text field has the tabEnabled property set to false so it is excluded from the automatic tab ordering this createTextField one_txt this getNextHighestDepth 10 10 100 22 one_txt border true one_txt type input this createTextField two_txt this getNextHighestDepth 10 40 100 22 two_txt border true two_txt type input this cre...

Page 754: ...roperty is flat This means that no attention is paid to the hierarchical relationships of objects in the SWF file All objects in the SWF file with tabIndex properties are placed in the tab order and the tab order is determined by the order of the tabIndex values If two objects have the same tabIndex value the one that goes first is undefined You shouldn t use the same tabIndex value for multiple o...

Page 755: ...et output _level0 my_txt TextField text Availability Flash Player 6 Usage my_txt text String Description Property indicates the current text in the text field Lines are separated by the carriage return character r ASCII 13 This property contains the normal unformatted text in the text field without HTML tags even if the text field is HTML Example The following example creates an HTML text field ca...

Page 756: ...em is FFFFFF Example The following ActionScript creates a text field and changes its color property to red this createTextField my_txt 99 10 10 100 300 my_txt text this will be red text my_txt textColor 0xFF0000 TextField textHeight Availability Flash Player 6 Usage my_txt textHeight Number Description Property indicates the height of the text Example The following example creates a text field and...

Page 757: ...t See Also TextField textHeight TextField type Availability Flash Player 6 Usage my_txt type String Description Property Specifies the type of text field There are two values dynamic which specifies a dynamic text field that cannot be edited by the user and input which specifies an input text field Example The following example creates two text fields username_txt and password_txt Text is entered ...

Page 758: ...d the text field Example The following example retrieves the URL of the SWF file that created the text field and a SWF file that loads into it this createTextField my_txt 1 10 10 100 22 trace my_txt _url var mclListener Object new Object mclListener onLoadInit function target_mc MovieClip trace target_mc _url var holder_mcl MovieClipLoader new MovieClipLoader holder_mcl addListener mclListener hol...

Page 759: ...mber setInterval updateDate 500 function updateDate Void today_date new Date TextField _visible Availability Flash Player 6 Usage my_txt _visible Boolean Description Property a Boolean value that indicates whether the text field my_txt is visible Text fields that are not visible _visible property set to false are disabled Example The following example creates a text field called my_txt A button ca...

Page 760: ...r true my_txt multiline true my_txt type input my_txt wordWrap true this createTextField width_txt this getNextHighestDepth 10 10 30 20 width_txt border true width_txt maxChars 3 width_txt restrict 0 9 width_txt type input width_txt text my_txt _width width_txt onChanged function my_txt _width this text this createTextField height_txt this getNextHighestDepth 70 10 30 20 height_txt border true hei...

Page 761: ...lability Flash Player 6 Usage my_txt _x Number Description Property an integer that sets the x coordinate of a text field relative to the local coordinates of the parent movie clip If a text field is on the main Timeline then its coordinate system refers to the upper left corner of the Stage as 0 0 If the text field is inside a movie clip that has transformations the text field is in the local coo...

Page 762: ...ce displays the current position of the mouse in relation to the Stage The textfield_txt instance displays the current position of the mouse pointer in relation to the my_txt instance Add the following ActionScript to a FLA or AS file this createTextField mouse_txt this getNextHighestDepth 10 10 200 22 mouse_txt border true this createTextField textfield_txt this getNextHighestDepth 220 10 200 22 ...

Page 763: ...y_txt _yscale 2 scaleDown_btn onRelease function my_txt _xscale 2 my_txt _yscale 2 See also TextField _x TextField _y TextField _yscale TextField _y Availability Flash Player 6 Usage my_txt _y Number Description Property the y coordinate of a text field relative to the local coordinates of the parent movie clip If a text field is in the main Timeline then its coordinate system refers to the upper ...

Page 764: ... the mouse position relative to the text field Example See the example for TextField _xmouse See also TextField _xmouse TextField _yscale Availability Flash Player 6 Usage my_txt _yscale Number Description Property the vertical scale of the text field as applied from the registration point of the text field expressed as a percentage The default registration point is 0 0 Example See the example for...

Page 765: ...ject to a TextField object s styleSheet property Method summary for the TextField StyleSheet class Event handler summary for the TextField StyleSheet class L Constructor for the TextField StyleSheet class Availability Flash Player 7 Usage new TextField StyleSheet TextField StyleSheet Method Description TextField StyleSheet clear Removes all styles from the style sheet object TextField StyleSheet g...

Page 766: ...Boolean if success trace Styles loaded var styles_array Array my_styleSheet getStyleNames trace styles_array join newline else trace Error loading CSS my_styleSheet load styles css The styles css file contains two styles called heading and mainbody so the following information writes to the log file Styles loaded heading mainBody The complete code for styles css is found in the example for TextFie...

Page 767: ...les_array length i trace t styles_array i trace else trace Error loading CSS Start the loading operation my_styleSheet load styles css clear_btn onRelease function my_styleSheet clear trace Styles cleared var styles_array Array my_styleSheet getStyleNames for var i 0 i styles_array length i trace t styles_array i trace TextField StyleSheet getStyle Availability Flash Player 7 Usage styleSheet getS...

Page 768: ...nLoad function success Boolean if success StyleSheetTracer display this else trace Error loading style sheet url Start the loading operation my_styleSheet load url static function display my_styleSheet StyleSheet Void var styleNames Array my_styleSheet getStyleNames if styleNames length trace This is an empty style sheet else for var i 0 i styleNames length i var styleName String styleNames i trac...

Page 769: ... StyleSheet setStyle TextField StyleSheet getStyleNames Availability Flash Player 7 Usage styleSheet getStyleNames Array Parameters None Returns An array Description Method returns an array that contains the names as strings of all of the styles registered in this style sheet Example This example creates a style sheet object named styleSheet that contains two styles heading and bodyText It then in...

Page 770: ...the file has finished loading The CSS file must reside in exactly the same domain as the SWF file that is loading it For more information about restrictions on loading data across domains see Applying Flex Security in Developing Flex Applications Example For an example of asynchronously loading style sheets using ActionScript 2 0 see the entry for TextField StyleSheet getStyle The following exampl...

Page 771: ...essfully loaded Returns Nothing Description Callback handler invoked when a TextField StyleSheet load operation has completed If the style sheet loaded successfully the success parameter is true If the document was not received or if an error occurred in receiving the response from the server the success parameter is false Example The following example loads the CSS file named styles css into the ...

Page 772: ...f the text was parsed successfully true or not false Description Method parses the CSS in cssText and loads the style sheet with it If a style in cssText is already in styleSheet the properties in styleSheet are retained and only the ones in cssText are added or changed in styleSheet To extend the native CSS parsing capability you can override this method by creating a subclass of the TextField St...

Page 773: ...e specified name to the style sheet object If the named style does not already exist in the style sheet it is added If the named style already exists in the style sheet it is replaced If the style parameter is null the named style is removed Flash Player creates a copy of the style object that you pass to this method Example The following code adds a style named emphasized to the style sheet mySty...

Page 774: ...l style object passed to setStyle While not necessary this step reduces memory usage because Flash Player creates a copy of the style object you pass to setStyle See also object initializer TextField StyleSheet transform Availability Flash Player 7 Usage styleSheet transform style Object TextFormat Parameters style An object that describes the style containing style rules as properties of the obje...

Page 775: ...is method class advCSS extends TextField StyleSheet override the transform method function transform style Object TextFormat for var z in style if z margin style marginLeft style z style marginRight style z delete style z break return super transform style end class definition ...

Page 776: ...the bold property to a defined value The code my_txt setTextFormat my_fmt only changes the bold property of the text field s default text format because the bold property is the only one defined in my_fmt All other aspects of the text field s default text format remain unchanged When TextField getTextFormat is invoked a TextFormat object is returned with all of its properties defined no property i...

Page 777: ...splayed If the target window is an empty string the text is displayed in the default target window _self If the url parameter is set to an empty string or to the value null you can get or set this property but the property will have no effect align The alignment of the paragraph represented as a string If left the paragraph is left aligned If center the paragraph is centered If right the paragraph...

Page 778: ...owing example creates a TextFormat object formats the stats_txt text field and creates a new text field to display the text in Define a TextFormat which is used to format the stats_txt text field var my_fmt TextFormat new TextFormat my_fmt bold true my_fmt font Arial my_fmt size 12 my_fmt color 0xFF0000 Create a text field to display the player s statistics this createTextField stats_txt 5000 10 0...

Page 779: ...he block indentation in points Block indentation is applied to an entire block of text that is to all lines of the text In contrast normal indentation TextFormat indent affects only the first line of each paragraph If this property is null the TextFormat object does not specify block indentation Example This example creates a text field with a border and sets the blockIndent to 20 this createTextF...

Page 780: ...ge my_fmt bullet Boolean Description Property a Boolean value that indicates that the text is part of a bulleted list In a bulleted list each paragraph of text is indented To the left of the first line of each paragraph a bullet symbol is displayed The default value is null Example The following example creates a new text field at runtime and enters a string with a line break into the field The Te...

Page 781: ... true my_txt wordWrap true my_txt border true my_txt text this is my first test field object text my_txt setTextFormat my_fmt TextFormat font Availability Flash Player 6 Usage my_fmt font String Description Property the name of the font for text in this text format as a string The default value is null which indicates that the property is undefined Example The following example creates a text fiel...

Page 782: ... width parameter is specified word wrapping is applied to the specified text This lets you determine the height at which a text box shows all of the specified text The ascent and descent measurements provide respectively the distance above and below the baseline for a line of text The baseline for the first line of text is positioned at the text field s origin plus its ascent measurement The width...

Page 783: ...d apply its properties var my_fmt TextFormat new TextFormat with my_fmt font Arial bold true Obtain metrics information for the text string with the specified formatting var metrics Object my_fmt getTextExtent my_str Create a text field just large enough to display the text this createTextField my_txt this getNextHighestDepth 100 100 metrics textFieldWidth metrics textFieldHeight my_txt border tru...

Page 784: ...metrics textFieldHeight my_txt wordWrap true my_txt border true Assign the text and the TextFormat object to the TextObject my_txt text textToDisplay my_txt setTextFormat my_fmt TextFormat indent Availability Flash Player 6 Usage my_fmt indent Number Description Property an integer that indicates the indentation from the left margin to the first character in the paragraph The default value is null...

Page 785: ...TextFormat new TextFormat myformat italic true mytext text this is my first test field object text mytext setTextFormat myformat TextFormat leading Availability Flash Player 6 Usage my_fmt leading Number Description Property the amount of vertical space called leading between lines The default value is null which indicates that the property is undefined Example The following example creates a text...

Page 786: ... TextFormat myformat leftMargin 20 mytext text this is my first test field object text mytext setTextFormat myformat TextFormat rightMargin Availability Flash Player 6 Usage my_fmt rightMargin Number Description Property the right margin of the paragraph in points The default value is null which indicates that the property is undefined Example The following example creates a text field and sets th...

Page 787: ...irst test field object text mytext setTextFormat myformat TextFormat tabStops Availability Flash Player 6 Usage my_fmt tabStops Array Description Property specifies custom tab stops as an array of non negative integers Each tab stop is specified in pixels If custom tab stops are not specified null the default tab stop is 4 average character width Example The following example creates two text fiel...

Page 788: ...rent window _blank specifies a new window _parent specifies the parent of the current frame and _top specifies the top level frame in the current window If the TextFormat url property is an empty string or null you can get or set this property but the property will have no effect Example The following example creates a text field with a hyperlink to the Macromedia website The example uses TextForm...

Page 789: ...tFormat new TextFormat myformat underline true mytext text this is my first test field object text mytext setTextFormat myformat TextFormat url Availability Flash Player 6 Usage my_fmt url String Description Property indicates the URL that text in this text format hyperlinks to If the url property is an empty string the text does not have a hyperlink The default value is null which indicates that ...

Page 790: ...umber Parameters startIndex An integer specifying the starting point in my_snap to search for the specified text Method Description TextSnapshot findText Returns the position of the first occurrence of specified text TextSnapshot getCount Returns the number of characters TextSnapshot getSelected Specifies whether any of the text in the specified range has been selected by TextSnapshot setSelected ...

Page 791: ...wing example illustrates how to use this method To use this code create a static text field that contains the text TextSnapshot Example var my_mc MovieClip this var my_snap TextSnapshot my_mc getTextSnapshot var index1 Number my_snap findText 0 Snap true var index2 Number my_snap findText 0 snap true var index3 Number my_snap findText 0 snap false trace index1 output 4 trace index2 output 1 trace ...

Page 792: ...om An integer that indicates the position of the first character of my_snap to be examined Valid values for from are 0 through TextSnapshot getCount 1 If from is a negative value 0 is used to An integer that is 1 the index of the last character in my_snap to be examined Valid values for to are 0 through TextSnapshot getCount The character indexed by the to parameter is not included in the extracte...

Page 793: ...er 7 or later Usage my_snap getSelectedText includeLineEndings Boolean String Parameters includeLineEndings An optional Boolean value that specifies whether newline characters are inserted into the returned string where appropriate The default value is false Returns A string that contains all the characters specified by the corresponding TextSnapshot setSelected command Description Method returns ...

Page 794: ...rns A string containing the characters in the specified range or an empty string if no characters are found in the specified range Description Method returns a string that contains all the characters specified by the from and to parameters If no characters are selected an empty string is returned To return all characters pass a value of 0 for from and TextSnapshot getCount or any very large number...

Page 795: ...character is found or if the font doesn t contain character metric information see Description Description Method lets you determine which character within a TextSnapshot object is on or near specified x y coordinates of the movie clip containing the text in my_snap If you omit or pass a value of 0 for maxDistance the location specified by the x y coordinates must lie inside the bounding box of my...

Page 796: ...single character the mouse pointer is over my_ts setSelected hitIndex hitIndex 1 true See also MovieClip getTextSnapshot MovieClip _x MovieClip _y TextSnapshot setSelectColor Availability Authoring Flash MX 2004 Playback SWF files published for Flash Player 6 or later playing in Flash Player 7 or later Usage my_snap setSelectColor hexColor Number Parameters hexColor The color used for the border p...

Page 797: ...getSelectedText false get the selected text trace theText output Txt trace firstCharIsSelected output true trace secondCharIsSelected output false When you test the SWF file you see a colored rectangle around the specified characters TextSnapshot setSelected Availability Authoring Flash MX 2004 Playback SWF files published for Flash Player 6 or later playing in Flash Player 7 or later Usage my_sna...

Page 798: ...tion for static text fields In some cases this behavior means that text that is selected won t appear to be selected onscreen Example The following example illustrates how to use this method To use this code place a static text field containing the text TextSnapshot Example on the Stage Note If characters don t appear to be selected when you run the code you must also place a dynamic text field on...

Page 799: ...that clip It is loaded using the MovieClipLoader class When you click the image the movie clip unloads from the SWF file var pic_mcl MovieClipLoader new MovieClipLoader pic_mcl loadClip http www macromedia com devnet mx blueprint articles performance spotlight_speterson jpg this createEmptyMovieClip pic_mc this getNextHighestDepth var listenerObject Object new Object listenerObject onLoadInit func...

Page 800: ...that was loaded by means of loadMovieNum from Flash Player To unload a SWF or image that was loaded with MovieClip loadMovie use unloadMovie instead of unloadMovieNum Example The following example loads an image into a SWF file When you click unload_btn the loaded content is removed loadMovieNum yourimage jpg 1 unload_btn onRelease function unloadMovieNum 1 See also MovieClip loadMovie unloadMovie...

Page 801: ... only with certain Mouse and MovieClip handlers the mouseDown mouseUp mouseMove keyDown and keyUp handlers for the Mouse class the onMouseMove onMouseDown onMouseUp onKeyDown and onKeyUp handlers for the MovieClip class It does not work with the Key class Example The following example show how to create a custom cursor called cursor_mc ActionScript is used to replace the mouse cursor with cursor_m...

Page 802: ...width properties and so on Method summary for the Video class Property summary for the Video class Video attachVideo Availability Flash Player 6 the ability to work with Flash Video FLV files was added in Flash Player 7 Usage my_video attachVideo source Object Void Parameters source A Camera object that is capturing video data or a NetStream object To drop the connection to the Video object pass n...

Page 803: ...ip attachAudio to route the audio to a movie clip you can then create a Sound object to control some aspects of the audio For more information see MovieClip attachAudio Example The following example plays live video locally var my_video Video my_video is a Video object var active_cam Camera Camera get my_video attachVideo active_cam The following example plays a previously recorded file named myVi...

Page 804: ...my_video deblocking Number Description Property a number that specifies the behavior for the deblocking filter that the video compressor applies as needed when streaming the video The following are acceptable values 0 the default Let the video compressor apply the deblocking filter as needed 1 Never use the deblocking filter 2 Always use the deblocking filter The deblocking filter has an effect on...

Page 805: ... height property of the Camera object that is capturing the video stream For FLV files this value is the height of the file that was exported as FLV You may want to use this property for example to ensure that the user is seeing the video at the same size at which it was captured regardless of the actual size of the Video object on the Stage Example Usage 1 The following example sets the height an...

Page 806: ...ailability Flash Player 6 Usage my_video smoothing Boolean Description Property a Boolean value that specifies whether the video should be smoothed interpolated when it is scaled For smoothing to work the player must be in high quality mode The default value is false no smoothing Example The following example uses a button called smoothing_btn to toggle the smoothing property that is applied to th...

Page 807: ...pecifying the width of the video stream in pixels For live streams this value is the same as the Camera width property of the Camera object that is capturing the video stream For FLV files this value is the width of the file that was exported as an FLV file You may want to use this property for example to ensure that the user is seeing the video at the same size at which it was captured regardless...

Page 808: ...808 Chapter 7 ActionScript for Flash ...

Page 809: ...t Logical NOT Right to left and Logical AND Left to right or Logical OR Flash 4 Left to right add String concatenation formerly Left to right instanceof Instance of Left to right lt Less than string version Left to right le Less than or equal to string version Left to right gt Greater than string version Left to right ge Greater than or equal to string version Left to right eq Equal string version...

Page 810: ...810 Appendix A Deprecated Flash 4 operators ...

Page 811: ...tion keys on page 813 Other keys on page 814 You can use key constants to intercept the built in behavior of keypresses For more information see Key class on page 295 Letters A to Z and standard numbers 0 to 9 The following table lists the keys on a standard keyboard for the letters A to Z and the numbers 0 to 9 with the corresponding ASCII key code values that are used to identify the keys in Act...

Page 812: ...12 Appendix B Keyboard Keys and Key Code Values L 76 M 77 N 78 O 79 P 80 Q 81 R 82 S 83 T 84 U 85 V 86 W 87 X 88 Y 89 Z 90 0 48 1 49 2 50 3 51 4 52 5 53 6 54 7 55 8 56 9 57 Letter or number key Key code ...

Page 813: ...ction keys on a standard keyboard with the corresponding ASCII key code values that are used to identify the keys in ActionScript Numeric keypad key Key code Numbpad 0 96 Numbpad 1 97 Numbpad 2 98 Numbpad 3 99 Numbpad 4 100 Numbpad 5 101 Numbpad 6 102 Numbpad 7 103 Numbpad 8 104 Numbpad 9 105 Multiply 106 Add 107 Enter 13 Subtract 109 Decimal 110 Divide 111 Function key Key code F1 112 F2 113 F3 1...

Page 814: ...ues that are used to identify the keys in ActionScript F10 This key is reserved by the system and cannot be used in ActionScript F11 122 F12 123 F13 124 F14 125 F15 126 Key Key code Backspace 8 Tab 9 Clear 12 Enter 13 Shift 16 Control 17 Alt 18 Caps Lock 20 Esc 27 Spacebar 32 Page Up 33 Page Down 34 End 35 Home 36 Left Arrow 37 Up Arrow 38 Right Arrow 39 Down Arrow 40 Insert 45 Delete 46 Help 47 F...

Page 815: ...Other keys 815 Num Lock 144 186 187 _ 189 191 192 219 220 221 222 Key Key code ...

Page 816: ...816 Appendix B Keyboard Keys and Key Code Values ...

Page 817: ...ors built in functions 41 C calling methods 21 casting data types 25 character sequences See strings child node 70 class files creating 48 class members and Singleton design pattern 61 and subclasses 62 created once per class 60 creating 60 example of using 62 classes and object oriented programming 46 classpaths 64 creating and using 51 creating external class files 48 creating properties and met...

Page 818: ...M Document Object Model XML 70 dot operators 38 dot syntax 14 dynamic classes 56 E ECMA 262 specification 10 encapsulation 47 equality operators 37 different from assignment operators 37 strict 37 errors name conflict 28 escape sequences 19 event handlers checking for XML data 68 defined 11 events defined 11 execution order operator associativity 32 operator precedence 32 expressions assigning mul...

Page 819: ...ction keys 813 letter and number keys 811 numeric keypad 813 other keys 814 keyboard ASCII key code values 811 keywords 12 listed 17 L languages using multiple in scripts 10 loaded data checking for 68 LoadVars object 70 local variables 28 and strict data typing 29 in functions 43 sample 28 logical operators 36 looping 40 actions 40 loops 40 M manipulating numbers 20 methods asynchronous 68 declar...

Page 820: ...rs 53 Q quotation marks including in strings 19 R reference data types 18 referencing variables 28 remote files communicating with 67 sites continuous connection 71 repeating actions 40 reserved words See keywords resources additional 6 runtime defined 6 S scripts commenting 16 declaring variables 29 semicolon 15 sending information in XML format 68 to remote files 67 URL encoded format 68 via TCP...

Page 821: ...coded format sending information 68 V values manipulating in expressions 31 variables about 27 assigning multiple 37 defined 13 determining data type 26 naming rules 27 passing content 30 referencing value 30 scoping 28 setting dynamically 38 testing 27 transferring between movie and server 70 using in scripts 29 W web applications continuous connection 71 X XML 70 DOM 70 hierarchy 70 sample varia...

Page 822: ...822 Index ...

Page 823: ...signment 120 equality 120 strict equality 122 greater than 124 greater than or equal to 124 bitwise right shift 125 bitwise right shift and assignment 126 bitwise unsigned right shift 127 bitwise unsigned right shift and assignment 128 conditional 99 bitwise XOR 105 bitwise XOR assignment 106 _accProps 235 _focusrect 532 _global object 171 _parent 666 _root 668 _soundbuftime 703 object initializer...

Page 824: ...hideBuiltInItems 521 ContextMenu onSelect 522 ContextMenuItem class 524 ContextMenuItem caption 526 ContextMenuItem copy 526 ContextMenuItem enabled 527 ContextMenuItem onSelect 528 ContextMenuItem separatorBefore 529 ContextMenuItem visible 529 continue 140 D Date class 260 Date getDate 263 Date getDay 263 Date getFullYear 264 Date getHours 264 Date getMilliseconds 265 Date getMinutes 266 Date ge...

Page 825: ...NTER 301 Key ESCAPE 302 Key getAscii 302 Key getCode 303 Key INSERT 305 Key isDown 305 Key isToggled 306 Key LEFT 307 Key onKeyDown 308 Key onKeyUp 308 Key PGDN 309 Key PGUP 310 Key removeListener 310 Key RIGHT 311 Key SHIFT 312 Key SPACE 312 Key TAB 313 Key UP 313 L LoadVars class 315 LoadVars addRequestHeader 316 LoadVars contentType 318 LoadVars getBytesLoaded 319 LoadVars getBytesTotal 320 Loa...

Page 826: ... class 554 MovieClip _alpha 558 MovieClip _currentframe 568 MovieClip _droptarget 571 MovieClip _focusrect 574 MovieClip _framesloaded 575 MovieClip _height 585 MovieClip _highquality 585 MovieClip _lockroot 592 MovieClip _name 596 MovieClip _parent 611 MovieClip _rotation 614 MovieClip _target 621 MovieClip _totalframes 622 MovieClip _url 624 MovieClip _visible 625 MovieClip _width 626 MovieClip ...

Page 827: ...2 MovieClipLoader addListener 633 MovieClipLoader getProgress 634 MovieClipLoader loadClip 635 MovieClipLoader onLoadComplete 638 MovieClipLoader onLoadError 639 MovieClipLoader onLoadInit 641 MovieClipLoader onLoadProgress 642 MovieClipLoader onLoadStart 644 MovieClipLoader removeListener 645 MovieClipLoader unloadClip 646 N NaN 184 NetConnection class 647 NetConnection connect 648 NetStream clas...

Page 828: ...ge addListener 704 Stage align 705 Stage height 706 Stage onResize 707 Stage removeListener 707 Stage scaleMode 708 Stage showMenu 708 Stage width 709 startDrag 711 static 206 stop 712 stopAllSounds 713 stopDrag 714 String class 408 String 208 String charAt 409 String charCodeAt 410 String concat 411 String fromCharCode 411 String indexOf 412 String lastIndexOf 413 String length 414 String slice 4...

Page 829: ... 725 TextField getDepth 726 TextField getFontList 727 TextField getNewTextFormat 727 TextField getTextFormat 728 TextField hscroll 729 TextField html 730 TextField htmlText 731 TextField length 731 TextField maxChars 732 TextField maxhscroll 732 TextField maxscroll 733 TextField menu 733 TextField mouseWheelEnabled 734 TextField multiline 735 TextField onChanged 736 TextField onKillFocus 737 TextF...

Page 830: ...eo deblocking 804 Video height 805 Video smoothing 806 Video width 807 void 227 W while 228 with 230 X XML class 445 XML addRequestHeader 447 XML appendChild 448 XML attributes 450 XML childNodes 450 XML cloneNode 451 XML contentType 453 XML createElement 454 XML createTextNode 454 XML docTypeDecl 456 XML firstChild 456 XML getBytesLoaded 457 XML getBytesTotal 458 XML hasChildNodes 459 XML ignoreW...

Reviews: