MACROMEDIA FLEX 2-PROGRAMMING ACTIONSCRIPT 3.0 Manual

Summary of FLEX 2-PROGRAMMING ACTIONSCRIPT 3.0

  • Page 1

    Programming actionscript 3.0 ad ob e ® fl ex ™ 2.

  • Page 2

    © 2006 adobe systems incorporated. All rights reserved. Flex 2 programming actionscript 3.0 if this guide is distributed with software that includes an end-user agreement, this guide, as well as the software described in it, is furnished under license and may be used or copied only in accordance wit...

  • Page 3

    3 contents part 1: overview of actionscript programming about this manual. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .11 using this manual . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12 accessing actionscript documenta...

  • Page 4

    4 contents advanced topics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 139 example: geometricshapes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 148 chapter 5: display programming . . . . . . . . . . . . . . . . . . . . . . . . ....

  • Page 5

    Contents 5 handling synchronous errors in an application . . . . . . . . . . . . . . . . . . .261 creating custom error classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 266 responding to error events and status . . . . . . . . . . . . . . . . . . . . . . . . . 267 comparing th...

  • Page 6

    6 contents flash.Text package . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .342 flash.Ui package . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .342 flash.Utils package . . . . . . . . . . . . . . . . . . . . . . . ....

  • Page 7

    Contents 7 loading content . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 467 cross-scripting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 470 accessing loaded media as data. . . . . . . . . . . . . . . . . . ....

  • Page 8

    8 contents.

  • Page 9

    9 1 part 1 overview of actionscript programming this part describes fundamental programming concepts in actionscript 3.0. The following chapters are included: about this manual . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11 chapter 1: introduction to actionscr...

  • Page 11

    11 about this manual this manual provides a foundation for developing applications in actionscript 3.0. To best understand the ideas and techniques described, you should already be familiar with general programming concepts such as data types, variables, loops, and functions. You should also underst...

  • Page 12

    12 about this manual using this manual this manual is divided into the following parts: the manual contains numerous sample files for important or commonly used classes to demonstrate application programming concepts for those apis. Sample files are packaged in ways to make them easier to load and u...

  • Page 13

    Accessing actionscript documentation 13 to understand the code samples in this manual, you don’t need to have prior experience using integrated development environments for actionscript, such as flex builder or the flash authoring tool. You will, however, want to refer to the documentation for those...

  • Page 14

    14 about this manual flex documentation if you use the flex development environment, you may want to consult these manuals: developer center the adobe developer center is a your resource for up-to-the-minute information on actionscript, articles about real-world application development, and informat...

  • Page 15

    15 1 chapter 1 introduction to actionscript 3.0 this chapter provides an overview of actionscript 3.0, the newest and most revolutionary version of actionscript. Contents about actionscript. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ....

  • Page 16

    16 introduction to actionscript 3.0 ■ a core language based on the upcoming ecmascript (ecma-262) edition 4 draft language specification ■ an xml api based on ecmascript for xml (e4x), as specified in ecma-357 edition 2 specification. E4x is a language extension to ecmascript that adds xml as a nati...

  • Page 17

    What’s new in actionscript 3.0 17 run-time exceptions actionscript 3.0 reports more error conditions than previous versions of actionscript. Run- time exceptions are used for common error conditions, improving the debugging experience and enabling you to develop applications that handle errors robus...

  • Page 18

    18 introduction to actionscript 3.0 ecmascript for xml (e4x) actionscript 3.0 implements ecmascript for xml (e4x), recently standardized as ecma- 357. E4x offers a natural, fluent set of language constructs for manipulating xml. In contrast to traditional xml-parsing apis, xml with e4x performs like...

  • Page 19

    What’s new in actionscript 3.0 19 dom3 event model document object model level 3 event model (dom3) provides a standard way of generating and handling event messages so that objects within applications can interact and communicate, maintaining their state and responding to change. Patterned after th...

  • Page 20

    20 introduction to actionscript 3.0 low-level data access various apis provide low-level access to data that was never before available in actionscript. For data that is being downloaded, the urlstream class, which is implemented by urlloader, provides access to data as raw binary data while it is b...

  • Page 21

    Compatibility with previous versions 21 the only exception to this rule is that an actionscript 2.0 swf file can replace itself with an actionscript 3.0 swf file, as long as the actionscript 2.0 swf file hasn't previously loaded anything into any of its levels. An actionscript 2.0 swf file can do th...

  • Page 22

    22 introduction to actionscript 3.0

  • Page 23

    23 2 chapter 2 getting started with actionscript this chapter provides a no-frills, step-by-step approach to building a simple actionscript 3.0 application. The actionscript 3.0 programming language can be used from within a number of different development environments, including macromedia flash fr...

  • Page 24

    24 getting started with actionscript 3. Create a flash or flex application file to run your code. In the flash authoring tool, this involves creating a new fla file, setting up the publish settings, adding user interface components to the application, and referencing the actionscript code. In the fl...

  • Page 25

    Options for organizing your code 25 many developers simplify the organization of their actionscript code in the flash authoring tool by placing code only in the first frame of a timeline, or on a specific layer in the flash document. This makes it easier to locate and maintain the code in your flash...

  • Page 26

    26 getting started with actionscript ■ actionscript class definition: a definition of an actionscript class, including its method and property definitions. When you define a class, you can access the actionscript code in the class by creating an instance of the class and using its properties, method...

  • Page 27

    Example: creating a basic application 27 designing your actionscript application you should have some idea about the application you want to build before you start building it. The representation of your design can be as simple as the name of the application and a brief statement of its purpose, or ...

  • Page 28

    28 getting started with actionscript 5. In the new actionscript file dialog box, select helloworld as the parent folder, type greeter.As the filename, and then click finish. A new actionscript editing window is displayed. Continue with “adding code to the greeter class” on page 28 . Adding code to t...

  • Page 29

    Example: creating a basic application 29 to create an actionscript application using flex builder: 1. Open the helloworld.Mxml file, and type the following code: layout="vertical" creationcomplete = "initapp()" > private var mygreeter:greeter = new greeter(); public function initapp():void { // says...

  • Page 30

    30 getting started with actionscript publishing and testing your actionscript application software development is an iterative process. You write some code, try to compile it, and edit the code until it compiles cleanly. You run the compiled application, test it to see if it fulfills the intended de...

  • Page 31

    Example: creating a basic application 31 2. Change the contents of the file to the following (new and changed lines are shown in boldface): package { public class greeter { /** * defines the names that should receive a proper greeting. */ public static var validnames:array = ["sammy", "frank", "dean...

  • Page 32

    32 getting started with actionscript the greeter class now has a number of new features: ■ the validnames array lists valid user names. The array is initialized to a list of three names when the greeter class is loaded. ■ the sayhello() method now accepts a user name and changes the greeting based o...

  • Page 33

    Example: creating a basic application 33 private var mygreeter:greeter = new greeter(); public function initapp():void { // says hello at the start, and asks for the user's name maintxt.Text = mygreeter.Sayhello(); } ]]> editable="false" /> mygreeter.Sayhello(usernametxt.Text);" /> 4. Save the edite...

  • Page 34

    34 getting started with actionscript.

  • Page 35

    35 3 chapter 3 actionscript language and syntax actionscript 3.0 comprises both the core actionscript language and the flash player application programming interface (api). The core language is the part of actionscript that implements the draft ecmascript (ecma-262), edition 4 draft language specifi...

  • Page 36

    36 actionscript language and syntax programmers familiar with object-oriented programming (oop) in java or c++ may think of objects as modules that contain two kinds of members: data stored in member variables or properties, and behavior accessible through methods. The ecmascript edition 4 draft, th...

  • Page 37

    Objects and classes 37 objects and classes in actionscript 3.0, every object is defined by a class. A class can be thought of as a template or a blueprint for a type of object. Class definitions can include variables and constants, which hold data values, and methods, which are functions that encaps...

  • Page 38

    38 actionscript language and syntax packages and namespaces packages and namespaces are related concepts. Packages allow you to bundle class definitions together in a way that facilitates code sharing and minimizes naming conflicts. Namespaces allow you to control the visibility of identifiers, such...

  • Page 39

    Packages and namespaces 39 many developers, especially those with java programming backgrounds, may choose to place only classes at the top level of a package. Actionscript 3.0, however, supports not only classes at the top level of a package, but also variables, functions, and even statements. One ...

  • Page 40

    40 actionscript language and syntax most of the flash player api is organized under the flash package. For example, the flash.Display package contains the display list api, and the flash.Events package contains the new event model. A detailed discussion of the flash player api packages can be found ...

  • Page 41

    Packages and namespaces 41 importing packages if you want to use a class that is inside a package, you must import either the package or the specific class. This differs from actionscript 2.0, where importing classes was optional. For example, consider the samplecode class example from earlier in th...

  • Page 42

    42 actionscript language and syntax when a package is created, the default access specifier for all members of that package is internal , which means that, by default, package members are only visible to other members of that package. If you want a class to be available to code outside the package, ...

  • Page 43

    Packages and namespaces 43 the compiler has no way of knowing which samplecode class to use. To resolve this conflict, you must use the fully qualified name of each class, as follows: var sample1:samples.Samplecode = new samples.Samplecode(); var sample2:langref.Samples.Samplecode = new langref.Samp...

  • Page 44

    44 actionscript language and syntax there are three basic steps to follow when using namespaces. First, you must define the namespace using the namespace keyword. For example, the following code defines the version1 namespace: namespace version1; second, you apply your namespace by using it instead ...

  • Page 45

    Packages and namespaces 45 if a namespace is defined within a package or a class, the namespace may not be visible to code outside that package or class unless the appropriate access control specifier is used. For example, the following code shows the flash_proxy namespace defined within the flash.U...

  • Page 46

    46 actionscript language and syntax you should bear in mind the following when applying namespaces: ■ you can apply only one namespace to each declaration. ■ there is no way to apply a namespace attribute to more than one definition at a time. In other words, if you want to apply your namespace to t...

  • Page 47

    Packages and namespaces 47 using namespaces you can find a real-world example of a namespace that is used to prevent name conflicts in the flash.Utils.Proxy class that is part of the flash player api. The proxy class, which is the replacement for the object.__resolve property from actionscript 2.0, ...

  • Page 48

    48 actionscript language and syntax import flash.Utils.Proxy; import flash.Utils.Flash_proxy; dynamic class myproxy extends proxy { flash_proxy override function callproperty(name:*, ...Rest):* { trace("method call intercepted: " + name); } } } if you create an instance of the myproxy class and call...

  • Page 49

    Packages and namespaces 49 the following example uses a user-defined namespace to group together two functions that reside in different packages. By grouping them into the same namespace, you can make both functions visible to a class or package through a single use namespace statement. This example...

  • Page 50

    50 actionscript language and syntax import example.Myinternal; use namespace myinternal; public class helper { private static var _timestamp:date; public static function sometask() { _timestamp = new date(); } myinternal static function get lastcalled():date { return _timestamp; } } } the fourth fil...

  • Page 51

    Variables 51 variables variables allow you to store values that you use in your program. To declare a variable, you must use the var statement with the variable name. In actionscript 2.0, use of the var statement is only required if you use type annotations. In actionscript 3.0, use of the var state...

  • Page 52

    52 actionscript language and syntax if you have more than one variable to declare, you can declare them all on one line of code by using the comma operator ( , ) to separate the variables. For example, the following code declares three variables on one line of code: var a:int, b:int, c:int; you can ...

  • Page 53

    Variables 53 if the variable name you use for your local variable is already declared as a global variable, the local definition hides (or shadows) the global definition while the local variable is in scope. The global variable will still exist outside of the function. For example, the following cod...

  • Page 54

    54 actionscript language and syntax an interesting implication of the lack of block-level scope is that you can read or write to a variable before it is declared, as long as it is declared before the function ends. This is because of a technique called hoisting , which means that the compiler moves ...

  • Page 55

    Data types 55 if you declare a variable, but do not declare its data type, the default data type * will apply, which actually means that the variable is untyped. If you also do not initialize an untyped variable with a value, its default value is undefined . For data types other than boolean, number...

  • Page 56

    56 actionscript language and syntax many programming languages distinguish between primitive values and their wrapper objects. Java, for example, has an int primitive and the java.Lang.Integer class that wraps it. Java primitives are not objects, but their wrappers are, which makes primitives useful...

  • Page 57

    Data types 57 in order to provide compile-time type checking, the compiler needs to know the data type information for the variables or expressions in your code. To explicitly declare a data type for a variable, add the colon operator ( : ) followed by the data type as a suffix to the variable name....

  • Page 58

    58 actionscript language and syntax trace("number: " + mynum); } } dynamictest(100) dynamictest("one hundred"); run-time type checking run-time type checking occurs in actionscript 3.0 whether you compile in strict mode or standard mode. Consider a situation in which the value 3 is passed as an argu...

  • Page 59

    Data types 59 run-time type checking also allows more flexible use of inheritance than does compile-time checking. By deferring type checking to run time, standard mode allows you to reference properties of a subclass even if you upcast . An upcast occurs when you use a base class to declare the typ...

  • Page 60

    60 actionscript language and syntax the is operator examines the proper inheritance hierarchy and can be used to check not only whether an object is an instance of a particular class, but also whether an object is an instance of a class that implements a particular interface. The following example c...

  • Page 61

    Data types 61 dynamic classes a dynamic class defines an object that can be altered at run time by adding or changing properties and methods. A class that is not dynamic, such as the string class, is a sealed class. You cannot add properties or methods to a sealed class at run time. You create dynam...

  • Page 62

    62 actionscript language and syntax methods created in this way, however, do not have access to any private properties or methods of the protean class. Moreover, even references to public properties or methods of the protean class must be qualified with either the this keyword or the class name. The...

  • Page 63

    Data types 63 null data type the null data type contains only one value, null . This is the default value for the string data type and all classes that define complex data types, including the object class. None of the other primitive data types, such as boolean, number, int and uint, contain the va...

  • Page 64

    64 actionscript language and syntax when you store integer values with the number data type, only the 52 bits of the significand are used. The number data type uses these 52 bits and a special hidden bit to represent integers from -9,007,199,254,740,992 (-2 53 ) to 9,007,199,254,740,992 (2 53 ). Fla...

  • Page 65

    Data types 65 object data type the object data type is defined by the object class. The object class serves as the base class for all class definitions in actionscript. The actionscript 3.0 version of the object data type differs from that of previous versions in three ways. First, the object data t...

  • Page 66

    66 actionscript language and syntax implicit conversions implicit conversions happen at run time in a number of contexts: ■ in assignment statements ■ when values are passed as function arguments ■ when values are returned from functions ■ in expressions using certain operators, such as the addition...

  • Page 67

    Data types 67 casting to int, uint, and number you can cast any data type into one of the three number types: int, uint, and number. If flash player is unable to convert the number for some reason, the default value of 0 is assigned for the int and uint data types, and the default value of nan is as...

  • Page 68

    68 actionscript language and syntax in actionscript 3.0, the number() function no longer supports octal, or base 8, numbers. If you supply a string with a leading zero to the actionscript 2.0 number() function, the number is interpreted as an octal number, and converted to its decimal equivalent. Th...

  • Page 69

    Data types 69 casting to boolean casting to boolean from any of the numeric data types (uint, int, and number) results in false if the numeric value is 0, and true otherwise. For the number data type, the value nan also results in false . The following example shows the results of casting the number...

  • Page 70

    70 actionscript language and syntax boolean variables get special treatment in strict mode in that you can assign values of any data type to a boolean variable without casting. Implicit coercion from all data types to the boolean data type occurs even in strict mode. In other words, unlike almost al...

  • Page 71

    Syntax 71 casting to string from an instance of the date class returns a string representation of the date that the instance contains. For example, the following example returns a string representation of the date class instance (the output shows result for pacific daylight time): var mydate:date = ...

  • Page 72

    72 actionscript language and syntax public function method1():void {} } using dot syntax, you can access the prop1 property and the method1() method using the instance name created in the following code: var mydotex:dotexample = new dotexample(); mydotex.Prop1 = “hello”; mydotex.Method1(); you can u...

  • Page 73

    Syntax 73 an array literal can be used to initialize an array. The following examples show two arrays that are initialized using array literals. You can use the new statement and pass the compound literal as a parameter to the array class constructor, but you can also assign literal values directly ...

  • Page 74

    74 actionscript language and syntax parentheses you can use parentheses ( () ) in three ways in actionscript 3.0. First, you can use parentheses to change the order of operations in an expression. Operations that are grouped inside parentheses are always executed first. For example, parentheses are ...

  • Page 75

    Syntax 75 keywords and reserved words reserved words are words that you cannot use as identifiers in your code because the words are reserved for use by actionscript. Reserved words include lexical keywords , which are removed from the program namespace by the compiler. The compiler will report an e...

  • Page 76

    76 actionscript language and syntax there are also several identifiers that are sometimes referred to as future reserved words . These identifiers are not reserved by actionscript 3.0, though some of them may be treated as keywords by products that incorporate actionscript 3.0. You might be able to ...

  • Page 77

    Operators 77 an error results if you attempt to assign an initial value to a constant in any other way. For example, if you attempt to set the initial value of maximum outside the class, a run-time error will occur. Class a { public const minimum:int = 0; public const maximum:int; } var a:a = new a(...

  • Page 78

    78 actionscript language and syntax some operators are overloaded , which means that they behave differently depending on the type or quantity of operands passed to them. The addition ( + ) operator is an example of an overloaded operator that behaves differently depending on the data type of the op...

  • Page 79

    Operators 79 for example, consider the less-than ( ) and greater-than ( > ) operators, which have the same precedence. If both operators are used in the same expression, the operator on the left is processed first because both operators are left-associative. This means that the following two stateme...

  • Page 80

    80 actionscript language and syntax primary operators the primary operators include those used for creating array and object literals, grouping expressions, calling functions, instantiating class instances, and accessing properties. All the primary operators, as listed in the following table, have e...

  • Page 81

    Operators 81 postfix operators the postfix operators take one operator and either increment or decrement the value. Although these operators are unary operators, they are classified separately from the rest of the unary operators because of their higher precedence and special behavior. When a postfi...

  • Page 82

    82 actionscript language and syntax multiplicative operators the multiplicative operators take two operands and perform multiplication, division, or modulo calculations. All the multiplicative operators, as listed in the following table, have equal precedence: additive operators the additive operato...

  • Page 83

    Operators 83 relational operators the relational operators take two operands, compare their values, and return a boolean value. All the relational operators, as listed in the following table, have equal precedence: equality operators the equality operators take two operands, compare their values, an...

  • Page 84

    84 actionscript language and syntax logical operators the logical operators take two operands and return a boolean result. The logical operators differ in precedence and are listed in the following table in order of decreasing precedence: conditional operator the conditional operator is a ternary op...

  • Page 85

    Conditionals 85 conditionals actionscript 3.0 provides three basic conditional statements that you can use to control program flow. If..Else the if..Else conditional statement allows you to test a condition and execute a block of code if that condition exists, or execute an alternative block of code...

  • Page 86

    86 actionscript language and syntax if..Else if you can test for more than one condition using the if..Else if conditional statement. For example, the following code not only tests whether the value of x exceeds 20, but also tests whether the value of x is negative: if (x > 20) { trace("x is > 20");...

  • Page 87

    Conditionals 87 switch the switch statement is useful if you have several execution paths that depend on the same condition expression. It provides functionality similar to a long series of if..Else if statements, but is somewhat easier to read. Instead of testing a condition for a boolean value, th...

  • Page 88

    88 actionscript language and syntax looping looping statements allow you to perform a specific block of code repeatedly using a series of values or variables. Adobe recommends that you always enclose the block of code in braces ( {} ). Although you can omit the braces if the block of code contains o...

  • Page 89

    Looping 89 { trace(myarray[i]); } // output: // one // two // three what you cannot do is iterate through the properties of an object if it is an instance of a user- defined class, unless the class is a dynamic class. Even with instances of dynamic classes, you will be able to iterate only through p...

  • Page 90

    90 actionscript language and syntax you can also iterate through the elements of an array, as this example shows: var myarray:array = ["one", "two", "three"]; for each (var item in myarray) { trace(item); } // output: // one // two // three you cannot iterate through the properties of an object if t...

  • Page 91

    Functions 91 } while (i // output: 5 functions functions are blocks of code that carry out specific tasks and can be reused in your program. There are two types of functions in actionscript 3.0: methods and function closures . Whether a function is a called a method or a function closure depends on ...

  • Page 92

    92 actionscript language and syntax defining your own functions there are two ways to define a function in actionscript 3.0: you can use a function statement or a function expression. The technique you choose depends on whether you prefer a more static or dynamic programming style. Define your funct...

  • Page 93

    Functions 93 an assignment statement with a function expression begins with the var keyword, followed by: ■ the function name ■ the colon operator ( : ) ■ the function class to indicate the data type ■ the assignment operator ( = ) ■ the function keyword ■ the parameters, in a comma-delimited list e...

  • Page 94

    94 actionscript language and syntax function statements provide a more consistent experience between the two compiler modes in that you can use dot syntax in both strict and standard mode to invoke a method declared using a function statement. This is not necessarily true for methods declared with a...

  • Page 95

    Functions 95 there are two subtle differences between function statements and function expressions that you should take into account when choosing which technique to use. The first difference is that function expressions do not exist independently as objects with regard to memory management and garb...

  • Page 96

    96 actionscript language and syntax the second difference between function statements and function expressions is that function statements exist throughout the scope in which they are defined, including in statements that appear before the function statement. Function expressions, by contrast, are d...

  • Page 97

    Functions 97 nested functions you can nest functions, which means that functions can be declared within other functions. A nested function is available only within its parent function unless a reference to the function is passed to external code. For example, the following code declares two nested f...

  • Page 98

    98 actionscript language and syntax in actionscript 3.0, all arguments are passed by reference because all values are stored as objects. However, objects that belong to the primitive data types, which includes boolean, number, int, uint, and string, have special operators that make them behave as if...

  • Page 99

    Functions 99 trace(objparam.X, objparam.Y); } var objvar:object = {x:10, y:15}; trace(objvar.X, objvar.Y); // 10 15 passbyref(objvar); // 11 16 trace(objvar.X, objvar.Y); // 11 16 the objparam parameter references the same object as the global objvar variable. As you can see from the trace statement...

  • Page 100

    100 actionscript language and syntax actionscript 3.0 allows function calls to include more parameters than those defined in the function definition, but will generate a compiler error in strict mode if the number of parameters is less than the number of required parameters. You can use the array as...

  • Page 101

    Functions 101 you should also be careful to avoid using the string “arguments” as a parameter name because it will shadow the arguments object. For example, if the function traceargarray() is rewritten so that an arguments parameter is added, the references to arguments in the function body refer to...

  • Page 102

    102 actionscript language and syntax // output: // 1 // 2 // 3 the ... (rest) parameter can also be used with other parameters, as long as it is the last parameter listed. The following example modifies the traceargarray() function so that its first parameter, x , is of type int, and the second para...

  • Page 103

    Functions 103 although it may seem strange to programmers new to actionscript, functions can have properties and methods, just as any other object can. In fact, every function has a read-only property named length that stores the number of parameters defined for the function. This is different from ...

  • Page 104

    104 actionscript language and syntax function scope a function’s scope determines not only where in a program that function can be called, but also what definitions the function can access. The same scope rules that apply to variable identifiers apply to function identifiers. A function declared in ...

  • Page 105

    Functions 105 function rectarea(y:int):int // function closure defined { return x * y } return rectarea; } function bar():void { var x:int = 2; var y:int = 4; var myproduct:function = foo(); trace( myproduct(4) ); // function closure called } bar(); // 160 methods behave similarly in that they also ...

  • Page 106

    106 actionscript language and syntax.

  • Page 107

    107 4 chapter 4 object-oriented programming in actionscript this chapter assumes a basic understanding of object-oriented programming (oop) principles such as abstraction, encapsulation, inheritance, and polymorphism. The chapter focuses on how to apply these principles using actionscript 3.0. Becau...

  • Page 108

    108 object-oriented programming in actionscript as far back as actionscript 1.0, actionscript programmers could use function objects to create constructs that resembled classes. Actionscript 2.0 added formal support for classes with keywords such as class and extends . Actionscript 3.0 not only cont...

  • Page 109

    Classes 109 public class bitmapdata {} } class attributes actionscript 3.0 allows you to modify class definitions using one of the following four attributes: for each of these attributes, except for internal , you must explicitly include the attribute to get the associated behavior. For example, if ...

  • Page 110

    110 object-oriented programming in actionscript class body the class body, which is enclosed by curly braces, is used to define the variables, constants, and methods of your class. The following example shows the declaration for the accessibility class in the flash player api: public final class acc...

  • Page 111

    Classes 111 } // in your script var myst:statictest = new statictest(); trace(statictest.Message); // static variable trace(myst.Message); // instance variable class property attributes in discussions of the actionscript object model, the term property means anything that can be a member of a class,...

  • Page 112

    112 object-oriented programming in actionscript for example, the following code creates a simple class named privateexample with one private variable, and then attempts to access the private variable from outside the class. In actionscript 2.0, compile-time access was prohibited, but the prohibition...

  • Page 113

    Classes 113 dynamic classes generally return the value undefined instead of generating an error when code external to a class attempts to access a private property. The following table shows that an error is generated only when the dot operator is used to access a private property in strict mode: th...

  • Page 114

    114 object-oriented programming in actionscript static properties are not inherited by subclasses, but the properties are part of a subclass’s scope chain. This means that within the body of a subclass, a static variable or method can be used without referencing the class in which it was defined. Fo...

  • Page 115

    Classes 115 code that is external to the staticvars class and any of its subclasses can reference the totalcount and max_num properties only through the class itself. For example, the following code works: trace(staticvars.Totalcount); // 0 trace(staticvars.Max_num); // 16 you cannot access static v...

  • Page 116

    116 object-oriented programming in actionscript methods are defined using the function keyword. You can use a function statement, such as the following: public function samplefunction():string {} or you can use a variable to which you assign a function expression, as follows: public var samplefuncti...

  • Page 117

    Classes 117 constructor methods can only be public, but the use of the public attribute is optional. You cannot use any of the other access control specifiers, including private , protected , or internal , on a constructor. You also cannot use a user-defined namespace with a constructor method. A co...

  • Page 118

    118 object-oriented programming in actionscript static methods static methods, also called class methods, are methods that are declared with the static keyword. Static methods, which are attached to a class rather than to an instance of a class, are useful for encapsulating functionality that affect...

  • Page 119

    Classes 119 within the body of an instance method, both static and instance variables are in scope, which means that variables defined in the same class can be referenced using a simple identifier. For example, the following class, customarray, extends the array class. The customarray class defines ...

  • Page 120

    120 object-oriented programming in actionscript { return this; } } var mytest:thistest = new thistest(); trace(mytest.Thisvalue() == mytest); // true inheritance of instance methods can be controlled with the keywords override and final . You can use the override attribute to redefine an inherited m...

  • Page 121

    Classes 121 instead, a user of the getset class will use something that appears to be a property named publicaccess , but that is really a pair of get and set accessor functions that operate on the private property named privateproperty . The following example instantiates the getset class, and then...

  • Page 122

    122 object-oriented programming in actionscript the following code defines a class named thistest, which contains a method named foo() that defines the bound method, and a method named bar() that returns the bound method. Code external to the class creates an instance of the thistest class, calls th...

  • Page 123

    Classes 123 enumerations with classes enumerations are custom data types that you create to encapsulate a small set of values. Actionscript 3.0 does not support a specific enumeration facility, unlike c++ with its enum keyword or java with its enumeration interface. You can, however, create enumerat...

  • Page 124

    124 object-oriented programming in actionscript a second technique for creating enumerations also involves creating a separate class with static properties for the enumeration. This technique differs, however, in that each of the static properties contains an instance of the class instead of a strin...

  • Page 125

    Classes 125 } return retday; } var dayofweek:day = getday(); you can also enhance the day class so that it associates an integer with each day of the week, and provides a tostring() method that returns a string representation of the day. You might want to enhance the day class in this manner as an e...

  • Page 126

    126 object-oriented programming in actionscript var sndchannel:soundchannel = mysound.Play(); } } } alternatively, you can embed an asset with the @embed() directive in an mxml tag definition. For more information, see “about embedding assets” in the flex 2 developer’s guide . Interfaces an interfac...

  • Page 127

    Interfaces 127 in the flash player api, the eventdispatcher class implements the ieventdispatcher interface by defining all of the ieventdispatcher interface methods and adding method bodies to each of the methods. The following code is an excerpt from the eventdispatcher class definition: public cl...

  • Page 128

    128 object-oriented programming in actionscript the flash player api follows a convention in which interface names begin with an uppercase i , but you can use any legal identifier as an interface name. Interface definitions are often placed at the top level of a package. Interface definitions cannot...

  • Page 129

    Interfaces 129 you do have some flexibility, however, in how you name the parameters of methods that you implement. Although the number of parameters and the data type of each parameter in the implemented method must match that of the interface method, the parameter names do not need to match. For e...

  • Page 130

    130 object-oriented programming in actionscript inheritance inheritance is a form of code reuse that allows programmers to develop new classes that are based on existing classes. The existing classes are often referred to as base classes or superclasses , while the new classes are usually called sub...

  • Page 131

    Inheritance 131 } var cir:circle = new circle(); trace(cir.Area()); // 3.141592653589793 var sq:square = new square(); trace(sq.Area()); // 1 because each class defines a data type, the use of inheritance creates a special relationship between a base class and a class that extends it. A subclass is ...

  • Page 132

    132 object-oriented programming in actionscript ... } other types of events require unique properties not available in the event class. These events are defined using subclasses of the event class so that new properties can be added to the properties defined in the event class. An example of such a ...

  • Page 133

    Inheritance 133 you can use the following example to see how each of the access control specifiers affects inheritance across package boundaries. The following code defines a main application class named accesscontrol and two other classes named base and extender. The base class is in a package name...

  • Page 134

    134 object-oriented programming in actionscript to see how the other access control specifiers affect compilation and execution of the preceding example, change the str variable’s access control specifier to private , protected , or internal after deleting or commenting out the following line from t...

  • Page 135

    Inheritance 135 the names of the parameters in the override method, however, do not have to match the names of the parameters in the base class, as long as the number of parameters and the data type of each parameter matches. The super statement when overriding a method, programmers often want to ad...

  • Page 136

    136 object-oriented programming in actionscript package { import flash.Display.Movieclip; public class overrideexample extends movieclip { public function overrideexample() { trace(currentlabel) } override public function get currentlabel():string { var str:string = "override: "; str += super.Curren...

  • Page 137

    Inheritance 137 the only way to access the static variable test is through the class object, as shown in the following code: base.Test; it is permissible, however, to define an instance property using the same name as a static property. Such an instance property can be defined in the same class as t...

  • Page 138

    138 object-oriented programming in actionscript import flash.Display.Movieclip; public class staticexample extends movieclip { public function staticexample() { var myext:extender = new extender(); } } } class base { public static var test:string = "static"; } class extender extends base { public fu...

  • Page 139

    Advanced topics 139 public function extender() { trace(test); // output: instance } } advanced topics this section begins with a brief history of actionscript and oop and continues with a discussion of the actionscript 3.0 object model and how it enables the new actionscript virtual machine (avm2) t...

  • Page 140

    140 object-oriented programming in actionscript to create a class in actionscript 1.0, you define a constructor function for that class. In actionscript, functions are actual objects, not just abstract definitions. The constructor function that you create serves as the prototypical object for instan...

  • Page 141

    Advanced topics 141 the shape class and the circle class are now linked together in an inheritance relationship that is commonly known as the prototype chain . The diagram illustrates the relationships in a prototype chain: the base class at the end of every prototype chain is the object class. The ...

  • Page 142

    142 object-oriented programming in actionscript actionscript 2.0 actionscript 2.0 introduced new keywords such as class , extends , public , and private , that allowed you to define classes in a way that is familiar to anyone who works with class- based languages like java and c++. It’s important to...

  • Page 143

    Advanced topics 143 the actionscript 3.0 class object a common object-oriented programming paradigm, most commonly associated with java and c++, uses classes to define types of objects. Programming languages that adopt this paradigm also tend to use classes to construct instances of the data type th...

  • Page 144

    144 object-oriented programming in actionscript the traits object the traits object, which is new in actionscript 3.0, was implemented with performance in mind. In previous versions of actionscript, name lookup could be a time-consuming process as flash player walked the prototype chain. In actionsc...

  • Page 145

    Advanced topics 145 the prototype chain, which was the only inheritance mechanism in previous versions of actionscript, serves only a secondary role in actionscript 3.0. The primary inheritance mechanism, fixed property inheritance, is handled internally by the traits object. A fixed property is a v...

  • Page 146

    146 object-oriented programming in actionscript unlike fixed property inheritance, however, prototype inheritance does not require the override keyword if you want to redefine a method in a subclass. For example. If you want to redefine the valueof() method in a subclass of the object class, you hav...

  • Page 147

    Advanced topics 147 the as3 namespace the existence of two separate inheritance mechanisms, fixed property inheritance and prototype inheritance, creates an interesting compatibility challenge with respect to the properties and methods of the core classes. Compatibility with the ecmascript, edition ...

  • Page 148

    148 object-oriented programming in actionscript actionscript 3.0 also provides compiler options for each set of properties so that you can apply the as3 namespace to your entire program. The -as3 compiler option represents the as3 namespace, and the -es compiler option represents the prototype inher...

  • Page 149

    Example: geometricshapes 149 defining the geometricshapes classes the geometricshapes application lets the user specify a type of geometric shape and a size. It then responds with a description of the shape, its area, and distance around its perimeter. The application user interface is trivial, incl...

  • Page 150

    150 object-oriented programming in actionscript the classes and interfaces that define the geometric shapes in this example are shown in the following diagram using unified modeling language (uml) notation: defining common behavior with interfaces this geometricshapes application deals with three ty...

  • Page 151

    Example: geometricshapes 151 } } the interface defines two methods: the getarea() method, which calculates and returns the area of the shape, and the describe() method, which assembles a text description of the shape’s properties. We also want to know the distance around the perimeter of each shape....

  • Page 152

    152 object-oriented programming in actionscript { // the formula is pi * radius^2. Return math.Pi * ((diameter / 2)^2); } public function getcircumference():number { // the formula is pi * radius * 2. Return math.Pi * diameter; } public function describe():string { var desc:string = "this shape is a...

  • Page 153

    Example: geometricshapes 153 public function getarea():number { // this method should be overridden in subclasses. Return 0; } public function getperimeter():number { return sidelength * numsides; } public function getsumofangles():number { if (numsides >= 3) { return ((numsides - 2) * 180); } else ...

  • Page 154

    154 object-oriented programming in actionscript the following code for the equilateraltriangle class show how the getarea() method is overridden: package com.Example.Programmingas3.Geometricshapes { public class equilateraltriangle extends regularpolygon { public function equilateraltriangle(len:num...

  • Page 155

    Example: geometricshapes 155 the describe() method also uses the super() statement, but in a different way—to invoke the regularpolygon superclass’ version of the describe() method. The equilateraltriangle.Describe() method first sets the desc string variable to a statement about the type of shape. ...

  • Page 156

    156 object-oriented programming in actionscript { switch (shapename) { case "triangle": return new equilateraltriangle(len); case "square": return new square(len); case "circle": return new circle(len); } return null; } public static function describeshape(shapetype:string, shapesize:number):string ...

  • Page 157

    Example: geometricshapes 157 say that you wanted to add a new shape, a pentagon, to this example application. You would create a new pentagon class that extends the regularpolygon class and defines its own versions of the getarea() and describe() methods. Then you would add a new pentagon option to ...

  • Page 158

    158 object-oriented programming in actionscript.

  • Page 159

    159 5 chapter 5 display programming display programming in actionscript 3.0 allows you to work with elements that appear on the stage of adobe flash player 9. This chapter describes the basic concepts for working with onscreen elements. You’ll learn the details about programmatically organizing visu...

  • Page 160

    160 display programming understanding the display architecture each application built with actionscript 3.0 has a hierarchy of displayed objects known as the display list . The display list contains all the visible elements in the application. Display elements fall into one or more of the following ...

  • Page 161

    Understanding the display architecture 161 you can access the stage through the stage property of any displayobject instance. For more information, see “setting stage properties” on page 173 . ■ display objects in actionscript 3.0, all elements that appear on screen in an application are types of di...

  • Page 162

    162 display programming core display classes the actionscript 3.0 flash.Display package includes classes for visual objects that can appear in flash player. The following illustration shows the subclass relationships of these core display object classes. The illustration shows the class inheritance ...

  • Page 163

    Understanding the display architecture 163 ■ sprite—a sprite object can contain graphics of its own, and it can contain child display objects. (the sprite class extends the displayobjectcontainer class). For more information, see “working with display object containers” on page 168 and “drawing vect...

  • Page 164

    164 display programming advantages of the actionscript 3.0 display list approach in actionscript 3.0, there are separate classes for different types of display objects. In actionscript 1.0 and 2.0, many of the same types of objects are all included in one class: the movieclip class. This individuali...

  • Page 165

    Understanding the display architecture 165 in actionscript 3.0, when you move a display object to a new position in the child list of a displayobjectcontainer instance, the other children in the display object container are repositioned automatically and assigned appropriate child index positions in...

  • Page 166

    166 display programming you can use off-list display objects to assemble complex display objects, such as those that have multiple display object containers containing multiple display objects. By keeping display objects off-list, you can assemble complicated objects without using the processing tim...

  • Page 167

    Working with display objects 167 working with display objects now that you understand the basic concepts of the stage, display objects, display object containers, and the display list, this section provides you with some more specific information about working with display objects in actionscript 3....

  • Page 168

    168 display programming any display objects that you create without using actionscript—for example, by adding an mxml tag in adobe flex builder 2 or by using a drawing tool in flash—are added to the display list. Although you do not add these display objects through actionscript, you can access them...

  • Page 169

    Working with display objects 169 mytextfield.Text = "hello"; this.Root.Addchild(mytextfield); in this code sample, this.Root points to the movieclip display object container that contains the code. In your actual code, you may specify a different container. Use the addchildat() method to add the chi...

  • Page 170

    170 display programming you can use the getchildat() method to verify the layer order of the display objects. The getchildat() method returns child objects of a container based on the index number you pass it. For example, the following code reveals names of display objects at different positions in...

  • Page 171

    Working with display objects 171 recall that a display object that is off the display list—one that is not included in a display object container that is a child of the stage—is known as an off-list display object. Traversing the display list as you’ve seen, the display list is a tree structure. At ...

  • Page 172

    172 display programming var url:urlrequest = new urlrequest("banana.Jpg"); pict.Load(url); pict.Name = "banana loader"; container.Addchild(title); container.Addchild(pict); the getchildat() method returns the child of the display list at a specific index position: trace(container.Getchildat(0) is te...

  • Page 173

    Working with display objects 173 if you use flex, you should know that flex defines many component display object classes, and these classes override the display list access methods of the displayobjectcontainer class. For example, the container class of the mx.Core package overrides the addchild() ...

  • Page 174

    174 display programming in addition, a user can choose to leave full-screen mode by switching focus to a different window or by pressing one of several key combinations: the escape key (all platforms), ctrl-w (windows), cmd-w (mac), or alt-f4 (windows). Stage scaling behavior for full-screen mode is...

  • Page 175

    Working with display objects 175 ... If you are using javascript in a web page to generate the swf-embedding tags, you must alter the javascript to add the allowfullscreen param tag/attribute. For example, if your html page uses the ac_fl_runcontent() function (which is used by both flex builder- an...

  • Page 176

    176 display programming when flash player dispatches an event object, that event object makes a round-trip journey from the stage to the display object where the event occurred. For example, if a user clicks on a display object named child1 , flash player dispatches an event object from the stage th...

  • Page 177

    Basics for working with the core display classes 177 the graphics class includes the following methods for easily drawing simple shapes: drawcircle() , drawellipse() , drawrect() , drawroundrect() , and drawroundrectcomplex() . Before calling drawing methods, define the line style, fill, or both by ...

  • Page 178

    178 display programming working with text the textfield class, which is in the flash.Text package, lets you work with dynamic and input text fields. Note that there is also a statictext class in the flash.Text package. However, you cannot instantiate statictext objects in actionscript; these are cre...

  • Page 179

    Basics for working with the core display classes 179 loading content dynamically you can load any of the following external display assets into an actionscript 3.0 application: ■ a swf file authored in actionscript 3.0—this file can be a sprite, movieclip, or any class that extends sprite. ■ an imag...

  • Page 180

    180 display programming the loaderinfo class once the file has loaded, a loaderinfo object is created. This object is a property of both the loader object and the loaded display object. The loaderinfo object is a property of the loader object through the contentloaderinfo property of the loader obje...

  • Page 181

    Basics for working with the core display classes 181 the following diagram shows the different uses of the loaderinfo object—for the instance of the main class of the swf file, for a loader object, and for an object loaded by the loader object: the loadercontext class when you load an external file ...

  • Page 182

    182 display programming ■ securitydomain —use this property only when loading a swf file (not an image). Specify this for a swf file from a domain other than that of the file containing the loader object. When you specify this option, flash player checks for the existence of a cross- domain policy f...

  • Page 183

    Basics for working with the core display classes 183 controlling actionscript 3.0 movie clips each movieclip object has a timeline, and also includes properties and methods for controlling the playhead and working with frames and scenes. Many properties and methods of the actionscript 1.0 and 2.0 mo...

  • Page 184

    184 display programming creating and manipulating bitmaps the bitmapdata class lets you manipulate the pixels of a bitmap object. This can be a bitmap that you loaded from a file, or one that you draw exclusively through one of the bitmapdata methods. Each bitmap object has a bitmapdata property tha...

  • Page 185

    Basics for working with the core display classes 185 { upstate = new textbuttonstate(0xffffff, txt); downstate = new textbuttonstate(0xcccccc, txt); hitteststate = upstate; overstate = upstate; addeventlistener(mouseevent.Click, buttonclicked); } public function buttonclicked(e:event) { trace("butto...

  • Page 186

    186 display programming working with video the video class is not in the flash.Display package, but it is a subclass of the displayobject class. To have a video attached to the video object, you must use the attachnetstream() method or the attachcamera() method. Here is a simple example that attache...

  • Page 187

    Example: spritearranger 187 example: spritearranger the spritearranger example application builds upon the geometric shapes example application described in chapter 4 (see “example: geometricshapes” on page 148 ). The spritearranger example application illustrates a number of concepts for dealing wi...

  • Page 188

    188 display programming defining the spritearranger classes the spritearranger application lets the user add a variety of display objects to the onscreen “canvas.” the drawingcanvas class defines a drawing area, a type of display object container, to which the user can add onscreen shapes. These ons...

  • Page 189

    Example: spritearranger 189 as the following example shows, the initcanvas() method defines various properties of the drawingcanvas object, which were passed as arguments to the constructor function: this.Linecolor = linecolor; this.Fillcolor = fillcolor; this.Width = 500; this.Height = 200; the ini...

  • Page 190

    190 display programming the geometricsprite class and its subclasses each display object the user can add to the canvas is an instance of one of the following subclasses of the geometricsprite class: ■ circlesprite ■ squaresprite ■ trianglesprite the geometricsprite class extends the flash.Display.S...

  • Page 191

    Example: spritearranger 191 adding display objects to the canvas when the user clicks the add shape button, the application calls the addshape() method of the drawingcanvas class. It instantiates a new geometricsprite by calling the appropriate constructor function of one of the geometricsprite subc...

  • Page 192

    192 display programming the interface for the application includes two text fields, selectedspritetxt and outputtxt . The text properties of these text fields are updated with information about the geometricsprite objects that have been added to the canvas or selected by the user. The geometricsprit...

  • Page 193

    Example: spritearranger 193 this.Selectionindicator.Graphics.Drawrect(-1, -1, this.Size + 1, this.Size + 1); this.Addchild(this.Selectionindicator); if this is not the first time the onmousedown() method is called, the method simply sets the selectionindicator shape’s visible property (inherited fro...

  • Page 194

    194 display programming rearranging display object layering the user interface for the application includes buttons labeled move back, move down, move up, and move to front. When the user clicks one of these buttons, the application calls the corresponding method of the drawingcanvas class: movetoba...

  • Page 195

    195 2 part 2 core actionscript 3.0 data types and classes this part describes the implementation of key actionscript 3.0 classes and data types, and provides strategies for using them. The following chapters are included: chapter 6: working with dates and times. . . . . . . . . . . . . . . . . . . 1...

  • Page 197

    197 6 chapter 6 working with dates and times timing might not be everything, but it's usually a key factor in software applications. Actionscript 3.0 provides powerful ways to manage calendar dates, times, and time intervals. Two main classes provide most of this timing functionality: the date class...

  • Page 198

    198 working with dates and times second, if given a single numeric parameter, the date() constructor treats that as the number of milliseconds since january 1, 1970, and returns a corresponding date object. Note that the millisecond value you pass in is treated as milliseconds since january 1, 1970,...

  • Page 199

    Managing calendar dates and times 199 ■ the day property, which is the day of the week in numeric format, with 0 standing for sunday ■ the hours property, in the range of 0 to 23 ■ the minutes property ■ the seconds property ■ the milliseconds property in fact, the date class gives you a number of w...

  • Page 200

    200 working with dates and times now it is easy to perform date arithmetic using standard time units. The following code sets a date value to one hour from the current time using the gettime() and settime() methods: var onehourfromnow:date = new date(); onehourfromnow.Settime(onehourfromnow.Gettime(...

  • Page 201

    Controlling time intervals 201 controlling time intervals when you develop applications using the flash authoring tool, you have access to the timeline, which provides a steady, frame-by-frame progression through your application. In pure actionscript projects, however, you must rely on other timing...

  • Page 202

    202 working with dates and times here is a small sample application showing the timer class in action: package { import flash.Display.Sprite; import flash.Events.Timerevent; import flash.Utils.Timer; public class shorttimer extends sprite { public function shorttimer() { // creates a new five-second...

  • Page 203

    Controlling time intervals 203 when you run this sample, you should see the following lines appear in your console or trace window at the rate of one line per second: tick 1 tick 2 tick 3 tick 4 tick 5 time's up! Timing functions in the flash.Utils package actionscript 3.0 contains a number of timin...

  • Page 204

    204 working with dates and times example: simple analog clock a simple analog clock example illustrates two of the date and time concepts discussed in this chapter: ■ getting the current date and time and extracting values for the hours, minutes, and seconds ■ using a timer to set the pace of an app...

  • Page 205

    Example: simple analog clock 205 the class has two important properties: ■ the face property, which is an instance of the analogclockface class ■ the ticker property, which is an instance of the timer class the simpleclock class uses a default constructor. The initclock() method takes care of the re...

  • Page 206

    206 working with dates and times starting the timer after creating the clock face, the initclock() method sets up a timer: // creates a timer that fires an event once per second ticker = new timer(1000); // designates the ontick() method to handle timer events ticker.Addeventlistener(timerevent.Time...

  • Page 207

    Example: simple analog clock 207 this method saves the current time in a variable, so the time can’t change in the middle of drawing the clock hands. Then it calls the showtime() method to display the hands, as the following shows: /** * displays the given date/time in that good old analog clock sty...

  • Page 208

    208 working with dates and times.

  • Page 209

    209 7 chapter 7 working with strings the string class contains methods that let you work with text strings. Strings are important in working with many objects. The methods described in this chapter are useful in working with strings used in objects such as textfield, statictext, xml, contextmenu, an...

  • Page 210

    210 working with strings var str2:string = new string(str1); var str3:string = new string(); // str3 == null the following two strings are equivalent: var str1:string = "hello"; var str2:string = new string("hello"); to use single quotation marks ( ' ) within a string literal defined with single quo...

  • Page 211

    Working with characters in strings 211 the length property every string has a length property, which is equal to the number of characters in the string: var str:string = "macromedia"; trace(str.Length); // 10 an empty string and a null string both have a length of 0, as the following example shows: ...

  • Page 212

    212 working with strings you can also use character codes to define a string using the fromcharcode() method, as the following example shows: var mystr:string = string.Fromcharcode(104,101,108,108,111,32,119,111,114,108,100,33); // sets mystr to "hello world!" comparing strings you can use the follo...

  • Page 213

    Concatenating strings 213 obtaining string representations of other objects you can obtain a string representation for any kind of object. All objects have a tostring() method for this purpose: var n:number = 99.47; var str:string = n.Tostring(); // str == "99.47" when using the + concatenation oper...

  • Page 214

    214 working with strings str = str + area; // str == "area = 28.274333882308138" however, you can use parentheses for grouping to provide context for the + operator, as the following example shows: trace("total: $" + 4.55 + 1.45); //"total: $4.551.45" trace("total: $" + (4.55 + 1.45)); //"total: $6"...

  • Page 215

    Finding substrings and patterns in strings 215 the slice() method functions similarly to the substring() method. When given two non- negative integers as parameters, it works exactly the same. However, the slice() method can take negative integers as parameters, in which case the character position ...

  • Page 216

    216 working with strings creating an array of substrings segmented by a delimiter you can use the split() method to create an array of substrings, which is divided based on a delimiter. For example, you can segment a comma-delimited or tab-delimited string into multiple strings. The following exampl...

  • Page 217

    Finding substrings and patterns in strings 217 finding matching substrings the search() method returns the index position of the first substring that matches a given pattern, as shown in this example: var str:string = "the more the merrier."; trace(str.Search("the")); // output: 9 // (this search is...

  • Page 218

    218 working with strings replacing matched substrings you can use the replace() method to search for a specified pattern in a string and replace matches with the specified replacement string, as the following example shows: var str:string = "she sells seashells by the seashore."; var pattern:regexp ...

  • Page 219

    Converting strings between uppercase and lowercase 219 function usdtoeuro(matchedsubstring:string, capturedmatch1:string, index:int, str:string):string { var usd:string = capturedmatch1; usd = usd.Replace(",", ""); var exchangerate:number = 0.853690; var euro:number = usd * exchangerate; const euros...

  • Page 220

    220 working with strings example: ascii art this ascii art example shows a number of features of working with the string class in actionscript 3.0, including the following: ■ the split() method of the string class is used to extract values from a character- delimited string (image information in a t...

  • Page 221

    Example: ascii art 221 the asciiart application files can be found in the folder samples/asciiart. The application consists of the following files: extracting tab-delimited values this example uses the common practice of storing application data separate from the application itself; that way, if the...

  • Page 222

    222 working with strings the file uses a specific tab-delimited format. The first line (row) is a heading row. The remaining lines contain the following data for each bitmap to be loaded: ■ the filename of the bitmap. ■ the display name of the bitmap. ■ the white-threshold and black-threshold values...

  • Page 223

    Example: ascii art 223 using string methods to normalize image titles one of the design decisions for this application is that all the image titles are displayed using a standard format, with the first letter of each word capitalized (except for a few words which are commonly not capitalized in engl...

  • Page 224

    224 working with strings as its name suggests, the capitalizefirstletter() method actually does the work of capitalizing the first letter of each word: /** * capitalizes the first letter of a single word, unless it's one of * a set of words that are normally not capitalized in english. */ private fu...

  • Page 225

    Example: ascii art 225 3. The remaining characters of the original word are extracted using substring(1) , which extracts a substring starting at index 1 (the second letter) through the end of the string (indicated by leaving off the second parameter of the substring() method). 4. The final word is ...

  • Page 226

    226 working with strings this code first defines a string instance named result that will be used to build up the ascii art version of the bitmap image. Next, it loops through individual pixels of the source bitmap image. Using several color-manipulation techniques (omitted here for brevity), it con...

  • Page 227

    227 8 chapter 8 working with arrays arrays allow you to store multiple values in a single data structure. You can use simple indexed arrays that store values using fixed ordinal integer indexes or complex associative arrays that store values using arbitrary keys. Arrays can also be multidimensional,...

  • Page 228

    228 working with arrays var myarray:array = ["one", "two", "three"]; trace(myarray); // output: one,two,three the array class also contains properties and methods that allow you to modify indexed arrays. These properties and methods apply almost exclusively to indexed arrays rather than associative ...

  • Page 229

    Indexed arrays 229 third, if you call the constructor and pass a list of elements as parameters, an array is created with elements corresponding to each of the parameters. The following code passes three arguments to the array constructor: var names:array = new array("john", "jane", "david"); trace(...

  • Page 230

    230 working with arrays removing array elements three methods of the array class— pop() , shift() , and splice() —allow you to remove elements from an array. The pop() method removes an element from the end of the array. In other words, it removes the element at the highest index number. The shift()...

  • Page 231

    Indexed arrays 231 trace(oceans[2]); // output: undefined trace(oceans.Length); // output: 5 you can truncate an array using an array’s length property. If you set the length property of an array to a length that is less than the current length of the array, the array is truncated, removing any elem...

  • Page 232

    232 working with arrays you may find that you need to sort your array without regard to case, or in descending order, or perhaps your array contains numbers that you want to sort numerically instead of alphabetically. The sort() method has an options parameter that allows you to alter each character...

  • Page 233

    Indexed arrays 233 { return 1; } else { return 0; } } trace(names); // output: john q. Smith,jane doe,mike jones names.Sort(orderlastname); trace(names); // output: jane doe,mike jones,john q. Smith the custom sort function orderlastname() uses a regular expression to extract the last name from each...

  • Page 234

    234 working with arrays { trace(poets[i].Name, poets[i].Born); } /* output: wang 701 dante 1265 blake 1757 cummings 1894 angelou 1928 */ generally, the sort() and sorton() methods modify an array. If you wish to sort an array without modifying the existing array, pass the array.Returnindexedarray co...

  • Page 235

    Indexed arrays 235 querying an array the remaining four methods of the array class— concat() , join() , slice() , tostring() —all query the array for information, but do not modify the array. The concat() and slice() methods both return new arrays, while the join() and tostring() methods both return...

  • Page 236

    236 working with arrays one issue to be aware of with the join() method is that any nested arrays are always returned with comma-separated values, no matter what separator you specify for the main array elements, as the following example shows: var nested:array = ["b","c","d"]; var letters:array = [...

  • Page 237

    Associative arrays 237 after the array is created using either an object literal or the object class constructor, you can add new values to the array using either the bracket operator ( [] ) or the dot operator ( . ). The following example adds two new values to monitorarray : monitorinfo["aspect ra...

  • Page 238

    238 working with arrays the following code creates three instances of the sprite class that serve as keys for the dictionary object. Each key is assigned a value of either groupa or groupb . The values can be of any data type, but in this example both groupa and groupb are instances of the object cl...

  • Page 239

    Associative arrays 239 use the for..In loop for direct access to the object keys of a dictionary object. You can also access the values of the dictionary object with the property access ( [] ) operator. The following code uses the previous example of the groupmap dictionary to show how to iterate th...

  • Page 240

    240 working with arrays if you use myobject as a key in a dictionary object, you are creating another reference to the original object. For example, the following code creates two references to an object—the myobject variable, and the key in the mymap object: import flash.Utils.Dictionary; var myobj...

  • Page 241

    Multidimensional arrays 241 two indexed arrays when you use two indexed arrays, you can visualize the result as a table or spreadsheet. The elements of the first array represent the rows of the table, while the elements of the second array represent the columns. For example, the following multidimen...

  • Page 242

    242 working with arrays associative array with an indexed array to make the individual arrays easier to access, you can use an associative array for the days of the week and an indexed array for the task lists. Using an associative array allows you to use dot syntax when referring to a particular da...

  • Page 243

    Advanced topics 243 cloning arrays the array class has no built-in method for making copies of arrays. You can create a shallow copy of an array by calling either the concat() or slice() methods with no arguments. In a shallow copy, if the original array has elements that are objects, only the refer...

  • Page 244

    244 working with arrays as mentioned previously, arrays in actionscript are not typed, but you can create a subclass of array that accepts elements of only a specific data type. The example in the following sections defines an array subclass named typedarray that limits its elements to values of the...

  • Page 245

    Advanced topics 245 the four overridden methods all use the as3 namespace instead of the public attribute because this example assumes that the compiler option -as3 is set to true and the compiler option -es is set to false . These are the default settings for adobe flex builder 2 and for adobe flas...

  • Page 246

    246 working with arrays { this[i] = args[i] } } } } the typedarray constructor shares most of the code from the array constructor, with only four changes to the code. First, the parameter list includes a new required parameter of type class that allows specification of the array’s data type. Second,...

  • Page 247

    Advanced topics 247 typedarray overridden methods the typedarray class overrides the four methods of the array class that are capable of adding elements to an array. In each case, the overridden method adds a type check that prevents the addition of elements that are not the correct data type. Subse...

  • Page 248

    248 working with arrays the splice() method takes an arbitrary list of arguments, but the first two arguments always refer to an index number and the number of elements to delete. This is why the overridden splice() method does type checking only for args array elements in index positions 2 or highe...

  • Page 249

    Example: playlist 249 example: playlist the playlist example demonstrates techniques for working with arrays, in the context of a music playlist application that manages a list of songs. These techniques are: ■ creating an indexed array ■ adding items to an indexed array ■ sorting an array of object...

  • Page 250

    250 working with arrays as with all objects, declaring an array instance is only half the job of creating an array. Before accessing an array instance’s properties or methods, it must be instantiated, which is done in the playlist class’s constructor. Public function playlist() { this._songs = new a...

  • Page 251

    Example: playlist 251 sorting the list of songs because the song instances that are managed by the playlist are complex objects, users of the application may wish to sort the playlist according to different properties, such as song title or year of publication. In the playlist application, the task ...

  • Page 252

    252 working with arrays sorting by property and specifying sort options the work of actually sorting the list of songs is performed by the playlist class in the sortlist() method, as follows: /** * sorts the list of songs according to the specified property. */ public function sortlist(sortproperty:...

  • Page 253

    Example: playlist 253 combining array elements into a character-delimited string in addition to using an array to maintain the song list in the playlist class, in this example arrays are also used in the song class to help manage the list of genres to which a given song belongs. Consider this snippe...

  • Page 254

    254 working with arrays.

  • Page 255

    255 9 chapter 9 handling errors to “handle” an error means you build logic into your application that responds to, or fixes, an error, generated either when an application is compiled or when a compiled application is running. When your application handles errors, something occurs as a response when...

  • Page 256

    256 handling errors types of errors when you develop and run applications, you encounter different types of errors and error terminology. The following list introduces the major error types and terms: ■ compile-time errors are raised by the actionscript compiler during code compilation. Compile-time...

  • Page 257

    Types of errors 257 ■ asynchronous errors are run-time errors that occur at various points during run time; they generate events and are caught by event listeners. An asynchronous operation is one in which a function initiates an operation, but doesn’t wait for it to complete. You can create an erro...

  • Page 258

    258 handling errors ■ uncaught exceptions are errors thrown with no corresponding logic (like a catch statement) to respond to them. If your application throws an error, and no appropriate catch statement or event handler can be found at the current or higher level to handle the error, the error is ...

  • Page 259

    Error handling in actionscript 3.0 259 actionscript 3.0 error handling elements actionscript 3.0 includes many tools for error handling, including: ■ error classes. In compliance with the ecmascript (ecma-262) edition 4 draft language specification, actionscript 3.0 includes a broad range of error c...

  • Page 260

    260 handling errors error handling strategies as long as your application doesn’t encounter a problematic condition, it may still run successfully if you don’t build error handling logic into your code. However, if you don’t actively handle errors and your application does encounter a problem, your ...

  • Page 261

    Handling synchronous errors in an application 261 { tf.Text = error.Tostring(); } if the readboolean() method threw an eoferror in the debugger version of flash player, the following message would be displayed in the tf text field: “eoferror: error #2030: end of file was encountered.” the same code ...

  • Page 262

    262 handling errors the finally statement encloses statements that will execute whether or not an error occurs in the try block. If there is no error, the statements within the finally block execute after the try block statements complete. If there is an error, the appropriate catch statement execut...

  • Page 263

    Handling synchronous errors in an application 263 throw new argumenterror("i am an argumenterror"); } catch (error:argumenterror) { trace(" " + error.Message); } catch (error:error) { trace(" " + error.Message); } several methods and properties in the flash player api throw run-time errors if they e...

  • Page 264

    264 handling errors catch (error:uint) { throw myerror; // catch unsigned integer errors. } catch (error:int) { throw myerror; // catch integer errors. } catch (error:number) { throw myerror; // catch number errors. } catch (error:*) { throw myerror; // catch any other error. } finally { myfunction(...

  • Page 265

    Handling synchronous errors in an application 265 1-234 ; public function simpleerror() { try { if (employee.Costcenter.Length() != 1) { throw new error("error, employee must have exactly one cost center assigned."); } } catch (error:error) { var errormessage:textfield = new textfield(); errormessag...

  • Page 266

    266 handling errors } catch (error:error) { trace("> " + error); } } catch (error:applicationerror) { trace("> " + error); } the output from the previous snippet would be the following: > > applicationerror: some error which will be rethrown > > applicationerror: some error which will be rethrown th...

  • Page 267

    Responding to error events and status 267 the following shows an example of using apperror in your project: try { throw new apperror("encountered custom apperror", 29); } catch (error:apperror) { trace(error.Errorid + ": " + error.Message) } responding to error events and status one of the most noti...

  • Page 268

    268 handling errors ■ status-based error events the status-based error events are related to the netstatus and status properties of the networking and communication classes. If flash player encounters a problem when reading or writing data, the value of the netstatus.Info.Level or status.Level prope...

  • Page 269

    Responding to error events and status 269 { mymp3.Load(new urlrequest(mp3)); mymp3.Play(); } catch(err:error) { trace(err.Message); // your error handling code here } mymp3.Addeventlistener(ioerrorevent.Io_error, errorhandler); } private function linkhandler(linkevent:textevent):void { playmp3(linke...

  • Page 270

    270 handling errors public class videoexample extends sprite { private var videourl:string = "video.Flv"; private var connection:netconnection; private var stream:netstream; public function videoexample() { connection = new netconnection(); connection.Addeventlistener(netstatusevent.Net_status, nets...

  • Page 271

    Comparing the error classes 271 comparing the error classes actionscript provides a number of predefined error classes. Many of these classes are used by flash player, but you can also use the same error classes in your own code. There are two main types of error classes in actionscript 3.0: actions...

  • Page 272

    272 handling errors referenceerror a referenceerror exception is thrown when a reference to an undefined property is attempted on a sealed (nondynamic) object. Versions of the actionscript compiler before actionscript 3.0 did not throw an error when access was attempted to a property that was undefi...

  • Page 273

    Comparing the error classes 273 typeerror the typeerror exception is thrown when the actual type of an operand is different from the expected type. For more information, see section 15.11.6.5 of the ecmascript specification at www.Ecma-international.Org/ publications/standards/ecma- 262.Htm , as wel...

  • Page 274

    274 handling errors actionscript core error classes in addition to the core ecmascript error classes, actionscript adds several classes of its own for actionscript-specific error conditions and error handling functionality. Because these classes are actionscript language extensions to ecmascript edi...

  • Page 275

    Comparing the error classes 275 flash.Error package error classes the flash.Error package contains error classes that are considered part of the flash player api. In contrast to the error classes just described, the flash.Error package communicates errors events that are specific to flash player. Cl...

  • Page 276

    276 handling errors memoryerror a memoryerror exception is thrown when a memory allocation request fails. By default, actionscript virtual machine 2 does not impose a limit on how much memory an actionscript program may allocate. On a desktop pc, memory allocation failures are infrequent. You see an...

  • Page 277

    Example: customerrors application 277 example: customerrors application the customerrors application demonstrates techniques for working with custom errors when building an application. These techniques are: ■ validating an xml packet ■ writing a custom error ■ throwing custom errors ■ notifying use...

  • Page 278

    278 handling errors ; } the xml packet is later displayed in a textarea component instance on the stage. This allows you to modify the xml packet before attempting to revalidate it. When the user clicks the validate button, the validatedata() method is called. This method validates the employee xml ...

  • Page 279

    Example: customerrors application 279 if a fatal error occurs during an attempt to validate the employee xml packet, the error message is displayed in an alert component, and the xmltext textarea component instance and validatebtn button component instance are disabled, as the following code shows: ...

  • Page 280

    280 handling errors building a custom validator the custom validator class contains a single method, validateemployeexml() . The validateemployeexml() method takes a single argument, employee , which is the xml packet that you wish to validate. The validateemployeexml() method is as follows: public ...

  • Page 281

    Example: customerrors application 281 the applicationerror class’s constructor method is as follows: public function applicationerror() { messages = ; } each error node in the xml object contains a unique numeric code and an error message. Error messages can be easily looked up by their error code u...

  • Page 282

    282 handling errors the final method in the applicationerror class is tostring(). This method overrides the function defined in the error class so that you can customize the presentation of the error message. The method returns a string that identifies the specific error number and message that occu...

  • Page 283

    Example: customerrors application 283 defining the warningerror class the warningerror class extends the applicationerror class and is nearly identical to the fatalerror class, except for a couple minor string changes and sets the error severity to applicationerror.Warning instead of applicationerro...

  • Page 284

    284 handling errors.

  • Page 285

    285 10 chapter 10 using regular expressions a regular expression describes a pattern that is used to find and manipulate matching text in strings. Regular expressions resemble strings, but they can include special codes to describe patterns and repetition. For example, the following regular expressi...

  • Page 286

    286 using regular expressions introduction to regular expressions a regular expression describes a pattern of characters. Regular expressions are typically used to verify that a text value conforms to a particular pattern (such as verifying that a user-entered phone number has the proper number of d...

  • Page 287

    Regular expression syntax 287 trace(str.Match(pattern)); // 337,4, 57, 33 the following methods of the string class take regular expressions as parameters: match() , replace() , search() , and split() . For more information on these methods, see “finding patterns in strings and replacing substrings”...

  • Page 288

    288 using regular expressions do not use the backslash escape character with quotation marks in regular expressions that are defined by using the forward slash delineators. Similarly, do not use the escape character with forward slashes in regular expressions that are defined with the new constructo...

  • Page 289

    Regular expression syntax 289 a metasequence, like a metacharacter, has special meaning in a regular expression. A metasequence is made up of more than one character. The following sections provide details on using metacharacters and metasequences. About metacharacters the following table summarizes...

  • Page 290

    290 using regular expressions about metasequences metasequences are sequences of characters that have special meaning in a regular expression pattern. The following table describes these metasequences: [ and ] defines a character class, which defines possible matches for a single character: /[aeiou]...

  • Page 291

    Regular expression syntax 291 character classes you use character classes to specify a list of characters to match one position in the regular expression. You define character classes with square brackets ( [ and ] ). For example, the following regular expression defines a character class that match...

  • Page 292

    292 using regular expressions however, the three characters listed in the following table do function as metacharacters, with special meaning, in character classes: for any of these characters to be recognized as literal characters (without the special metacharacter meaning), you must precede the ch...

  • Page 293

    Regular expression syntax 293 you can also use the \x nn ascii character code to specify a range by ascii value. For example, the following character class matches any character from a set of extended ascii characters (such as é and ê ): /[\x80-\x9a]/ negated character classes when you use a caret (...

  • Page 294

    294 using regular expressions you can use quantifiers within parenthetical groupings that have quantifiers applied to them. For example, the following quantifier matches strings such as word and word-word-word : /\w+(-\w+)*/ by default, regular expressions perform what is known as greedy matching. A...

  • Page 296

    296 using regular expressions using groups with quantifiers if you do not use a group, a quantifier applies to the character or character class that precedes it, as the following shows: var pattern:regexp = /ab*/ ; // matches the character a followed by // zero or more occurrences of the character b...

  • Page 297

    Regular expression syntax 297 using groups to capture substring matches when you define a standard parenthetical group in a pattern, you can later refer to it in the regular expression. This is known as a backreference , and these sorts of groups are known as capturing groups . For example, in the f...

  • Page 298

    298 using regular expressions a special type of noncapturing group is the lookahead group, of which there are two types: the positive lookahead group and the negative lookahead group. Use (?= and ) to define a positive lookahead group, which specifies that the subpattern in the group must match at t...

  • Page 299

    Regular expression syntax 299 flags and properties the following table lists the five flags that you can set for regular expressions. Each flag can be accessed as a property of the regular expression object. Note that these properties are read-only. You can set the flags ( g , i , m , s , x ) when y...

  • Page 300

    300 using regular expressions when the g flag is set, the sting.Match() method returns multiple matches, as follows: var str:string = "she sells seashells by the seashore."; var pattern:regexp = /sh\w*/g; // the same pattern, but this time the g flag is set. Trace(str.Match(pattern)); // output: she...

  • Page 301

    Regular expression syntax 301 note that only the character signals the end of a line. The following characters do not: ■ return ( \r ) character ■ unicode line-separator ( \u2028 ) character ■ unicode paragraph-separator ( \u2029 ) character the s (dotall) flag if the s ( dotall or “dot all”) fla...

  • Page 302

    302 using regular expressions the lastindex property the lastindex property specifies the index position in the string at which to start the next search. This property affects the exec() and test() methods called on a regular expression that has the g flag set to true . For example, consider the fol...

  • Page 303

    Methods for using regular expressions with strings 303 methods for using regular expressions with strings the regexp class includes two methods: exec() and test() . In addition to the exec() and test() methods of the regexp class, the string class includes the following methods that let you match re...

  • Page 304

    304 using regular expressions trace(result.Index, "\t", pattern.Lastindex, "\t", result); result = pattern.Exec(str); } //output: // 0 3 she // 10 19 seashells // 27 35 seashore string methods that use regexp parameters the following methods of the string class take regular expressions as parameters...

  • Page 305

    Example: a wiki parser 305 defining the wikiparser class the wikiparser class includes methods that convert wiki input text into the equivalent html output. This is not a very robust wiki conversion application, but it does illustrate some good uses of regular expressions for pattern matching and st...

  • Page 306

    306 using regular expressions the parentheses in the regular expression define a capturing group, and the replace() method refers to this group by using the $1 code in the replacement string. The g ( global ) flag in the regular expression ensures that the replace() method replaces all matches in th...

  • Page 307

    Example: a wiki parser 307 the ^ and $ symbols the regular expression match the beginning and end of a line. The m ( multiline ) flag in the regular expression causes the regular expression to match the ^ symbol against the start of a line, not simply the start of the string. The replace() method re...

  • Page 308

    308 using regular expressions the call to the replace() method employs the regular expression and assembles the replacement html string, using backreferences. The urltoatag() method then calls the emailtoatag() method, which uses similar techniques to replace e-mail patterns with html hyperlink stri...

  • Page 309

    Example: a wiki parser 309 const eurosymbol:string = string.Fromcharcode(8364); // € return euro.Tofixed(2) + " " + eurosymbol; } note that args[1] represents the captured parenthetical group matched by the usdprice regular expression. This is the numerical portion of the u.S. Dollar string: that is...

  • Page 310

    310 using regular expressions.

  • Page 311

    311 11 chapter 11 working with xml actionscript 3.0 includes a group of classes based on the ecmascript for xml (e4x) specification (ecma-357 edition 2). These classes include powerful and easy-to-use functionality for working with xml data. Using e4x, you will be able to develop code with xml data ...

  • Page 312

    312 working with xml a quick introduction to xml this chapter assumes that you are familiar with basic xml concepts. However, even if you are new to xml, you may be able to get started working with basic xml methods by using the information in this chapter. As a basic introduction, consider the foll...

  • Page 313

    The e4x approach to xml processing 313 since many server-side applications use xml to structure data, you can use the xml classes in actionscript to create sophisticated rich internet applications, such as those that connect to web services. A web service is a means to connect applications—for examp...

  • Page 314

    314 working with xml often, your application will load xml data from an external source, such as a web service or a rss feed. However, for clarity, the examples in this chapter assign xml data as literals. As the following code shows, e4x includes some intuitive operators, such as the dot ( . ) and ...

  • Page 315

    Xml objects 315 xml objects an xml object may represent an xml element, attribute, comment, processing instruction, or text element. An xml object is classified as having either simple content or complex content . An xml object that has child nodes is classified as having complex content. An xml obj...

  • Page 316

    316 working with xml for details on these properties, see the actionscript 3.0 language reference . Xml methods the following methods allow you to work with the hierarchical structure of xml objects: ■ appendchild() ■ child() ■ childindex() ■ children() ■ descendants() ■ elements() ■ insertchildafte...

  • Page 317

    Xmllist objects 317 the following methods are for working with and determining certain types of xml content: ■ comments() ■ hascomplexcontent() ■ hassimplecontent() ■ nodekind() ■ processinginstructions() ■ text() the following methods are for conversion to strings and for formatting xml objects: ■ ...

  • Page 318

    318 working with xml the following methods allow you to work with xmllist object attributes: ■ attribute() ■ attributes() the following methods allow you to you work with xmllist properties: ■ hasownproperty() ■ propertyisenumerable() the following methods are for working with and determining certai...

  • Page 319

    Initializing xml variables 319 initializing xml variables you can assign an xml literal to an xml object, as follows: var myxml:xml = burger 3.95 fries 1.45 as the following snippet shows, you can also use the new constructor to create an instance of an xml object from a string that contains xml dat...

  • Page 320

    320 working with xml var loader:urlloader = event.Target as urlloader; if (loader != null) { externalxml = new xml(loader.Data); trace(externalxml.Toxmlstring()); } else { trace("loader is not a urlloader!"); } } to read xml data from a socket connection, use the xmlsocket class. For more informatio...

  • Page 321

    Assembling and transforming xml objects 321 as the following example shows, you can also use curly brace operators ( { and } ) to pass data by reference (from other variables) when constructing xml objects: var ids:array = [121, 122, 123]; var names:array = [["murphy","pat"], ["thibaut","jean"], ["s...

  • Page 322

    322 working with xml traversing xml structures one of the powerful features of xml is its ability to provide complex, nested data via a linear string of text characters. When you load data into an xml object, actionscript parses the data and loads its hierarchical structure into memory (or it sends ...

  • Page 323

    Traversing xml structures 323 accessing parent and child nodes the parent() method returns the parent of an xml object. You can use the ordinal index values of a child list to access specific child objects. For example, consider an xml object myxml that has two child properties named book . Each chi...

  • Page 324

    324 working with xml accessing attributes use the @ symbol (the attribute identifier operator) to access attributes in an xml or xmllist object, as shown in the following code: var employee:xml = wu erin ; trace(employee.@id); // 6401 you can use the * wildcard symbol with the @ symbol to access all...

  • Page 325

    Traversing xml structures 325 filtering by attribute or element value you can use the parentheses operators— ( and ) —to filter elements with a specific element name or attribute value. Consider the following xml object: var x:xml = zmed sue data analyst mcgee chuck jr. Data analyst the following ex...

  • Page 326

    326 working with xml similarly, the final line of following code generates an error because there is no b property of the second p element: var doc:xml = hello, bob. Hello. ; trace(doc.P.(b == 'bob')); to avoid these errors, you can identify the properties that have the matching attributes or elemen...

  • Page 327

    Using xml namespaces 327 the for..In statement lets you iterate over a set of property names in an xmllist: var total:number = 0; for (var pname:string in myxml.Item) { total += myxml.Item.@quantity[pname] * myxml.Item.Price[pname]; } the for each..In statement lets you iterate through the propertie...

  • Page 328

    328 working with xml the xml class includes the following methods for working with namespaces: addnamespace() , inscopenamespaces() , localname() , name() , namespace() , namespacedeclarations() , removenamespace() , setlocalname() , setname() , and setnamespace() . The default xml namespace directi...

  • Page 329

    Xml type conversion 329 if you use the trace() method without specifying tostring() or toxmlstring() , the data is converted using the tostring() method by default, as this code shows: var myxml:xml = burger 3.95 ; trace(myxml.Item[0].Menuname); // burger when using the trace() method to debug code,...

  • Page 330

    330 working with xml { myxml.Total.Children()[0] = number(myxml.Total.Children()[0]) + number(item.Price.Children()[0]); } trace(myxml.Total); // 4.35; if this code did not use the number() function, the code would interpret the + operator as the string concatenation operator, and the trace() method...

  • Page 331

    Example: loading rss data from the internet 331 the rss format is widely used to syndicate news via xml. A simple rss data file may look like the following: http://www.Nws.Noaa.Gov/alerts/ak.Html alaska - watches, warnings and advisories short term forecast - taiya inlet, klondike highway (alaska) h...

  • Page 332

    332 working with xml the rssviewer application files can be found in the folder samples/rssviewer. The application consists of the following files: reading and parsing xml data the rssparser class includes an xmlloaded() method that converts the input rss data, stored in the rssxml variable, into an...

  • Page 333

    Example: loading rss data from the internet 333 assembling xmllist data the html data (an xmllist object) is of the following form: itemtitle itemdescription more... The first lines of the method clear the default xml namespace: default xml namespace = new namespace(); the default xml namespace dire...

  • Page 334

    334 working with xml extracting the title of the rss feed and sending a custom event the xmlloaded() method sets a rsstitle string variable, based on information in the source rss xml data: rsstitle = rssxml.Channel.Title.Tostring(); finally, the xmlloaded() method generates an event, which notifies...

  • Page 335

    335 3 part 3 flash player apis this part provides in-depth strategies for working with important features that are implemented in packages and classes specific to adobe flash player 9. The following chapters are included: chapter 12: flash player api overview . . . . . . . . . . . . . . . . . . . . ...

  • Page 337

    337 12 chapter 12 flash player api overview this chapter describes the adobe flash player 9 packages provided with the actionscript 3.0 language. The flash player api refers to all packages, classes, functions, properties, constants, events, and errors that are in the flash package. They are unique ...

  • Page 338

    338 flash player api overview contents flash.Accessibility package . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .338 flash.Display package . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .338 flash...

  • Page 339

    Flash.Events package 339 in actionscript 2.0, nearly all visual elements were controlled by the movieclip class or handled “behind the scenes” by flash player. Low-level control of objects was not available. In actionscript 3.0, the api to control visual elements is defined more logically, by functi...

  • Page 340

    340 flash player api overview flash.External package the flash.External package contains only the externalinterface class, which was introduced in flash player 8 as a replacement for the fscommand() function. Externalinterface enables communication between actionscript and the flash player container...

  • Page 341

    Flash.Printing package 341 flash.Media package the flash.Media package contains classes for working with audio and video streams that are either prerecorded or that stream from the client computer that is running flash player. The sound class and its supporting classes let you work with external mp3...

  • Page 342

    342 flash player api overview flash.Profiler package this package contains the showredrawregions() function, which can be useful for debugging code. For more information, see the flash.Profiler package in the actionscript 3.0 language reference . Flash.System package the flash.System package contain...

  • Page 343

    Flash.Xml package 343 flash.Utils package this package provides various utility classes, such as bytearray, which lets you access and work with data on the byte level, and the timer class, which lets you run code on a specified time sequence. This package also contains a number of package-level func...

  • Page 344

    344 flash player api overview.

  • Page 345

    345 13 chapter 13 handling events an event handling system allows programmers to respond to user input and system events in a convenient way. The new actionscript 3.0 event model is not only convenient, but also standards-compliant, and well integrated with the new adobe flash player 9 display list....

  • Page 346

    346 handling events introduction to event handling you can think of events as occurrences of any kind in your swf file that are of interest to you as a programmer. For example, most swf files support user interaction of some sort— whether it's something as simple as responding to a mouse click or so...

  • Page 347

    How actionscript 3.0 event handling differs from earlier versions 347 how actionscript 3.0 event handling differs from earlier versions the most noticeable difference between event handling in actionscript 3.0 and event handling in previous versions of actionscript is that in actionscript 3.0 there ...

  • Page 348

    348 handling events unfortunately, the syntax used by the various event models overlap in various ways, and differ in others. For example, in actionscript 2.0, some properties, such as textfield.Onchanged , can be used as either a callback function or an event listener. However, the syntax for regis...

  • Page 349

    How actionscript 3.0 event handling differs from earlier versions 349 not all default behaviors can be prevented. For example, flash player generates a mouseevent object when a user double-clicks a word in a textfield object. The default behavior, which cannot be prevented, is that the word under th...

  • Page 350

    350 handling events the event flow flash player dispatches event objects whenever an event occurs. If the event target is not on the display list, flash player dispatches the event object directly to the event target. For example, flash player dispatches the progress event object directly to a urlst...

  • Page 351

    The event flow 351 if a user clicks on child1 node , flash player dispatches an event object into the event flow. As the following image shows, the object’s journey starts at stage , moves down to parent node , then moves to child1 node, and then “bubbles” back up to stage , moving through parent no...

  • Page 352

    352 handling events to find out how a particular event type behaves, you can either check the api documentation or examine the event object's properties. Examining the event object’s properties is described in the following section. Event objects event objects serve two main purposes in the new even...

  • Page 353

    Event objects 353 some two dozen event types are associated with the event class itself and are represented by event class constants, some of which are shown in the following excerpt from the event class definition: package flash.Events { public class event { // class constants public static const a...

  • Page 354

    354 handling events the bubbles property an event is said to bubble if its event object participates in the bubbling phase of the event flow, which means that the event object is passed from the target node back through its ancestors until it reaches the stage. The event.Bubbles property stores a bo...

  • Page 355

    Event objects 355 for complex swf files, especially those in which buttons are routinely decorated with smaller child objects, the target property may not be used frequently because it will often point to a button’s child object instead of the button. In these situations, the common practice is to a...

  • Page 356

    356 handling events stopping event flow you can call either the event.Stoppropogation() method or the event.Stopimmediatepropogation() method to prevent an event object from continuing on its way through the event flow. The two methods are nearly identical and differ only in whether the current node...

  • Page 357

    Event listeners 357 subclasses of the event class for many events, the common set of properties defined in the event class is sufficient. Other events, however, have unique characteristics that cannot be captured by the properties available in the event class. For these events, the flash player api ...

  • Page 358

    358 handling events in the actionscript 3.0 event model, there is no distinction between an event listener and a listener function. Actionscript 3.0 does not have an eventlistener interface, and listener functions can be defined outside a class or as part of a class. Moreover, listener functions do ...

  • Page 359

    Event listeners 359 when a user interacts with the resulting swf file by clicking on the square, flash player generates the following trace output: clickhandler detected an event of type: click the this keyword refers to: [object global] notice that the event object is passed as an argument to click...

  • Page 360

    360 handling events trace("the this keyword refers to: " + this); } } when a user interacts with the resulting swf file by clicking on the red square, flash player generates the following trace output: clickhandler detected an event of type: click the this keyword refers to: [object childsprite] not...

  • Page 361

    Event listeners 361 } } } import flash.Display.Sprite; import flash.Events.Mouseevent; class childsprite extends sprite { public function childsprite() { graphics.Beginfill(0xff0000); graphics.Drawrect(0,0,100,100); graphics.Endfill(); addeventlistener(mouseevent.Click, mylistenerobj.Clickhandler); ...

  • Page 362

    362 handling events { public interface ieventdispatcher { function addeventlistener(eventname:string, listener:object, usecapture:boolean=false, priority:integer=0, useweakreference:boolean=false):boolean; function removeeventlistener(eventname:string, listener:object, usecapture:boolean=false):bool...

  • Page 363

    Event listeners 363 the priority parameter of the addeventlistener() method is not an official part of the dom level 3 event model. It is included in actionscript 3.0 to provide you with more flexibility in organizing your event listeners. When you call addeventlistener() , you can set the priority ...

  • Page 364

    364 handling events checking for existing event listeners the final two methods of the ieventdispatcher interface provide useful information about the existence of event listeners. The haseventlistener() method returns true if an event listener is found for a specific event type on a particular disp...

  • Page 365

    Example: alarm clock 365 example: alarm clock the alarm clock example consists of a clock that allows the user to specify a time at which an alarm will go off, as well as a message to be displayed at that time. The alarm clock example builds on the simpleclock application from chapter 6, “working wi...

  • Page 366

    366 handling events providing notification when something happens is the job that events are made for. The alarmclock class exposes the alarm event, which other objects can listen for in order to perform desired actions. In addition, the alarmclock class uses an instance of the timer class to determ...

  • Page 367

    Example: alarm clock 367 the timer instance defined in the alarmclock class is named alarmtimer . The initclock() method, which performs necessary setup operations for the alarmclock instance, does two things with the alarmtimer variable. First, the variable is instantiated with parameters instructi...

  • Page 368

    368 handling events this method does several things, including storing the alarm message and creating a date object ( alarmtime ) representing the actual moment in time when the alarm is to go off. Of most relevance to the current discussion, in the final several lines of the method, the alarmtimer ...

  • Page 369

    Example: alarm clock 369 other code can register to be notified of the alarmclock class’s alarm event by calling the addeventlistener() method that alarmclock inherits from eventdispatcher. When an alarmclock instance is ready to notify other code that its alarm event has been raised, it does so by ...

  • Page 370

    370 handling events * @param message the text to display when the alarm goes off. */ public function alarmevent(message:string = "alarm!") { super(alarm); this.Message = message; } ... } the best way to create a custom event object class is to define a class that extends the event class, as shown in...

  • Page 371

    371 14 chapter 14 networking and communication the flash.Net package contains classes to send and receive data across the internet—for example, to load content from remote urls, to communicate with other flash player instances, and to connect to remote websites. In earlier versions of actionscript, ...

  • Page 372

    372 networking and communication working with external data when you build large actionscript applications, you often need to communicate with server- side scripts, or load data from external xml or text files. This behavior has changed significantly between actionscript 2.0 and actionscript 3.0. In...

  • Page 373

    Working with external data 373 the urlloader.Load() method (and optionally the urlloader class’s constructor) takes a single parameter, request , which is a urlrequest class object. A urlrequest object contains all of the information for a single http request, such as the target url, request method ...

  • Page 374

    374 networking and communication when you define variables within the urlvariables constructor or within the urlvariables.Decode() method, you need to make sure that you url-encode the ampersand ( & ) character because it has a special meaning and acts as a delimiter. For example, when you pass an a...

  • Page 375

    Working with external data 375 once the data has loaded, the event.Complete event is dispatched, and the contents of the external document are available to use in the urlloader’s data property, as the following code shows: private function completehandler(event:event):void { var loader2:urlloader = ...

  • Page 376

    376 networking and communication the following code demonstrates how setting the urlloader.Dataformat property to urlloaderdataformat.Variables allows you to automatically parse loaded data into a urlvariables object: package { import flash.Display.Sprite; import flash.Events.*; import flash.Net.Url...

  • Page 377

    Working with external data 377 as the following example shows, loading xml from an external file is the same as loading urlvariables. You can create a urlrequest instance and a urlloader instance and use them to download a remote xml document. When the file has completely downloaded, the event.Compl...

  • Page 378

    378 networking and communication communicating with external scripts in addition to loading external data files, you can also use the urlvariables class to send variables to a server-side script and process the server’s response. This is useful, for example, if you are programming a game and want to...

  • Page 379

    Connecting to other flash player instances 379 connecting to other flash player instances the localconnection class lets you communicate between different flash player instances, such as a swf in an html container or in an embedded or stand-alone player. This allows you to build very versatile appli...

  • Page 380

    380 networking and communication there are three ways to add callback methods to your localconnection objects: ■ subclass the localconnection class and add methods. ■ set the localconnection.Client property to an object that implements the methods. ■ create a dynamic class that extends localconnecti...

  • Page 381

    Connecting to other flash player instances 381 the localconnection.Client property indicates the object callback methods that should be invoked. In the previous code, the client property was set to a new instance of a custom class, customclient. The default value for the client property is the curre...

  • Page 382

    382 networking and communication the following code defines a local connection object that acts as a server and accepts incoming calls from other flash player instances: package { import flash.Net.Localconnection; import flash.Display.Sprite; public class serverlc extends sprite { public function se...

  • Page 383

    Connecting to other flash player instances 383 } public function closehandler(event:timerevent):void { fscommand("quit"); } } } to create a localconnection server, call the localconnection.Connect() method and provide a unique connection name. If you already have a connection with the specified name...

  • Page 384

    384 networking and communication connecting to swf documents in different domains to allow communications only from specific domains, you call the allowdomain() or allowinsecuredomain() method of the localconnection class and pass a list of one or more domains that are allowed to access this localco...

  • Page 385

    Socket connections 385 if you implement communication between swf files in different domains, you specify a connectionname parameter that begins with an underscore ( _ ). Specifying the underscore makes the swf file with the receiving localconnection object more portable between domains. Here are th...

  • Page 386

    386 networking and communication socket class introduced in actionscript 3.0, the socket class enables actionscript to make socket connections and to read and write raw binary data. It is similar to the xmlsocket class, but does not dictate the format of the received and transmitted data. The socket...

  • Page 387

    Socket connections 387 to create a socket connection, you must create a server-side application to wait for the socket connection request and send a response to the swf file. This type of server-side application can be written in a programming language such as java, python, or perl. To use the xmlso...

  • Page 388

    388 networking and communication when you invoke the xmlsocket.Connect() method, flash player opens a tcp/ip connection to the server and keeps that connection open until one of the following occurs: ■ the xmlsocket.Close() method of the xmlsocket class is called. ■ no more references to the xmlsock...

  • Page 389

    Socket connections 389 { socket = new serversocket(port); incoming = socket.Accept(); readerin = new bufferedreader(new inputstreamreader(incoming.Getinputstream())); printout = new printstream(incoming.Getoutputstream()); printout.Println("enter exit to exit.\r"); out("enter exit to exit.\r"); bool...

  • Page 390

    390 networking and communication to connect to the xmlsocket from your actionscript application, you need to create a new instance of the xmlsocket class, and call the xmlsocket.Connect() method while passing a host name and port number, as follows: var xmlsock:xmlsocket = new xmlsocket(); xmlsock.C...

  • Page 391

    Storing local data 391 new shared object instances can be created using the static sharedobject.Getlocal() or sharedobject.Getremote() methods. The getlocal() method attempts to load a locally persistent shared object that is available only to the current client, whereas the getremote() method attem...

  • Page 392

    392 networking and communication } trace(so.Data.Now); trace("sharedobject is " + so.Size + " bytes"); so.Flush(); when using the flush() method to write shared objects to a user’s hard drive, you should be careful to check whether the user has explicitly disabled local storage using the flash playe...

  • Page 393

    Storing local data 393 { trace(i + ":\t" + so.Data[i]); } creating a secure sharedobject when you create either a local or remote sharedobject using getlocal() or getremote() , there is an optional parameter named secure that determines whether access to this shared object is restricted to swf files...

  • Page 394

    394 networking and communication working with file upload and download the filereference class lets you add the ability to upload and download files between a client and a server. Users are prompted to select a file to upload or a location for download from a dialog box (such as the open dialog box ...

  • Page 395

    Working with file upload and download 395 filereference class the filereference class allows you to upload and download files between a user’s computer and a server. An operating system dialog box prompts the user to select a file to upload or a location for download. Each filereference object refer...

  • Page 396

    396 networking and communication ------------ij5ae0ae0km7gi3km7ei4ch2ei4gl6 content-disposition: form-data; name="filename" sushi.Jpg ------------ij5ae0ae0km7gi3km7ei4ch2ei4gl6 content-disposition: form-data; name="filedata"; filename="sushi.Jpg" content-type: application/octet-stream test file ----...

  • Page 397

    Working with file upload and download 397 (actual file data,,,) ------------ij5gi3gi3ei4gi3ei4km7gi3km7km7 content-disposition: form-data; name="upload" submit query ------------ij5gi3gi3ei4gi3ei4km7gi3km7km7-- uploading files to a server to upload files to a server, first call the browse() method t...

  • Page 398

    398 networking and communication { var request:urlrequest = new urlrequest("http://www.[yourdomain].Com/ fileuploadscript.Cfm") try { fileref.Upload(request); } catch (error:error) { trace("unable to upload file."); } } function completehandler(event:event):void { trace("uploaded"); } when you attem...

  • Page 399

    Working with file upload and download 399 ■ the url parameter contains an invalid protocol. The filereference.Upload() method must use either http or https. If you create a server script in coldfusion to accept a file upload from flash player, you can use code similar to the following: ')#" nameconf...

  • Page 400

    400 networking and communication $files = array(); while ($file = readdir($directory)) { array_push($files, array('./images/'.$file, filectime('./images/ '.$file))); } usort($files, sorter); if (count($files) > $maximum_file_count) { $files_to_delete = array_splice($files, 0, count($files) - $maximu...

  • Page 401

    Working with file upload and download 401 } function completehandler(event:event):void { trace("uploaded"); } the previous example creates a new urlvariables object that you pass to the remote server- side script. In previous versions of actionscript, you could pass variables to the server upload sc...

  • Page 402

    402 networking and communication to set the default name to currentnews.Xml instead of index.Xml, specify the defaultfilename parameter, as the following snippet shows: var request:urlrequest = new urlrequest("index.Xml"); var filetodownload:filereference = new filereference(); filetodownload.Downlo...

  • Page 403

    Working with file upload and download 403 the following code demonstrates the coldfusion script, download.Cfm, that downloads one of two files from the server, depending on the value of a url variable: deletefile="no" /> deletefile="no" /> filereferencelist class the filereferencelist class lets the...

  • Page 404

    404 networking and communication { var request:urlrequest = new urlrequest("http://www.[yourdomain].Com/ fileuploadscript.Cfm"); var file:filereference; var files:filereferencelist = filereferencelist(event.Target); var selectedfilearray:array = files.Filelist; for (var i:uint = 0; i { file = filere...

  • Page 405

    Example: building a telnet client 405 the telnet application files can be found in the samples/telnet folder. The application consists of the following files: telnet socket application overview the main telnetsocket.Mxml file is responsible for creating the user interface (ui) for the entire applica...

  • Page 406

    406 networking and communication the first line of code imports the telnet class from the custom com.Example.Programmingas.Socket package. The second line of code declares an instance of the telnet class, telnetclient , that will be initialized later by the connect() method. Next, the connect() meth...

  • Page 407

    Example: building a telnet client 407 public function telnet(server:string, port:int, output:textarea) { serverurl = server; portnumber = port; ta = output; socket = new socket(); socket.Addeventlistener(event.Connect, connecthandler); socket.Addeventlistener(event.Close, closehandler); socket.Addev...

  • Page 408

    408 networking and communication displaying messages from the socket server whenever a message is received from the socket server, or an event occurs, the custom msg() method is called. This method appends a string to the textarea on the stage and calls a custom setscroll() method, which causes the ...

  • Page 409

    Example: uploading and downloading files 409 the fileio application files are found in the samples/fileio folder. The application consists of the following files: fileio application overview the file io application contains the user interface that allows a user to upload or download files using flas...

  • Page 410

    410 networking and communication this code places a progressbar component instance and two button component button instances on the stage. When the user clicks the upload button ( startupload) , an operating system dialog box is launched that allows the user to select a file to upload to a remote se...

  • Page 411

    Example: uploading and downloading files 411 /** * define reference to the download progressbar component. */ private var pb:progressbar; /** * define reference to the "cancel" button which will immediately stop * the current download in progress. */ private var btn:button; the first variable, downl...

  • Page 412

    412 networking and communication beginning the file download when the user clicks the download button component instance on the stage, the startdownload() method is to initiate the file download process. The following excerpt shows the startdownload() method: /** * begin downloading the file specifi...

  • Page 413

    Example: uploading and downloading files 413 monitoring a file’s download progress as a file downloads from a remote server to the user’s computer, the progress event ( progressevent.Progress ) is dispatched at regular intervals. Whenever the progress event is dispatched, the progresshandler() metho...

  • Page 414

    414 networking and communication pb.Label = "download cancelled"; btn.Enabled = false; } first, the code stops the file transfer immediately, preventing any further data from downloading. Next, the progress bar’s label property is updated to notify the user that the download has been successfully ca...

  • Page 415

    Example: uploading and downloading files 415 beginning a file upload the file upload is initiated when the user clicks on the upload button on the stage, which invokes the fileupload.Startupload() method. This method calls the browse() method of the filereference class which causes the operating sys...

  • Page 416

    416 networking and communication.

  • Page 417

    417 15 chapter 15 working with geometry the flash.Geom package contains classes that define geometric objects such as points, rectangles, and transformation matrixes. You use these classes to define the properties of objects that are used in other classes. Contents using point objects . . . . . . . ...

  • Page 418

    418 working with geometry finding the distance between two points you can use the distance() method of the point class to find the distance between two points in a coordinate space. For example, the following code finds the distance between the registration points of two display objects, circle1 and...

  • Page 419

    Using point objects 419 moving a display object by a specified angle and distance you can use the polar() method of the point class to move a display object a specific distance by a specific angle. For example, the following code moves the mydisplayobject object 100 pixels by 60 degrees: import flas...

  • Page 420

    420 working with geometry using rectangle objects a rectangle object defines a rectangular area. A rectangle object has a position, defined by the x and y coordinates of its top-left corner, a width property, and a height property. You can define these properties for a new rectangle object by invoki...

  • Page 421

    Using rectangle objects 421 similarly, as the following example shows, if you change the bottom or right property of a rectangle object, the position of its top-left corner does not change, so it is resized accordingly: import flash.Geom.Rectangle; var x1:number = 0; var y1:number = 0; var width1:nu...

  • Page 422

    422 working with geometry finding unions and intersections of rectangle objects you use the union() method to find the rectangular region formed by the boundaries of two rectangles: import flash.Display.*; import flash.Geom.Rectangle; var rect1:rectangle = new rectangle(0, 0, 100, 100); trace(rect1)...

  • Page 423

    Using matrix objects 423 other uses of rectangle objects rectangle objects are used in the following methods and properties: using matrix objects the matrix class represents a transformation matrix that determines how to map points from one coordinate space to another. You can perform various graphi...

  • Page 424

    424 working with geometry defining matrix objects although you could define a matrix by directly adjusting the properties ( a , b , c , d , tx , ty ) of a matrix object, it is easier to use the createbox() method. This method includes parameters that let you directly define the scaling, rotation, an...

  • Page 425

    Using matrix objects 425 matrix.Rotate(rotation); mydisplayobject.Transform.Matrix = matrix; the first line sets a matrix object to the existing transformation matrix used by the mydisplayobject display object (the matrix property of the transformation property of the mydisplayobject display object)...

  • Page 426

    426 working with geometry the following examples show gradients in which the rotation parameter of the creategradientbox() method differs as indicated, but all other settings stay the same: width = 100; height = 100; rotation = 0; tx = 0; ty = 0; width = 100; height = 100; rotation = math.Pi/4; // 4...

  • Page 427

    Using matrix objects 427 the following examples show the effects on a green-to-blue linear gradient in which the rotation , tx , and ty parameters of the creategradientbox() method differ as indicated, but all other settings stay the same: the width , height , tx , and ty parameters of the creategra...

  • Page 428

    428 working with geometry the following code produces the last radial gradient illustrated: import flash.Display.Shape; import flash.Display.Gradienttype; import flash.Geom.Matrix; var type:string = gradienttype.Radial; var colors:array = [0x00ff00, 0x000088]; var alphas:array = [1, 1]; var ratios:a...

  • Page 429

    Example: applying a matrix transformation to a display object 429 the application provides an interface for adjusting the parameters of the matrix transformation, as follows: when the user clicks the transform button, the application applies the appropriate transformation. The original display objec...

  • Page 430

    430 working with geometry the displayobjecttransformer application files can be found in the folder samples/ displayobjecttransformer. The application consists of the following files: defining the matrixtransformer class the matrixtransformer class includes static methods that apply geometric transf...

  • Page 431

    Example: applying a matrix transformation to a display object 431 the skew() method the skew() method skews the matrix by adjusting the b and c properties of the matrix. An optional parameter, unit , determines the units used to define the skew angle, and if necessary, the method converts the angle ...

  • Page 432

    432 working with geometry the translate() method the translate() method simply applies the dx and dy translation factors by calling the translate() method of the matrix object, as follows: sourcematrix.Translate(dx, dy); return sourcematrix; the rotate() method the rotate() method converts the input...

  • Page 433

    433 16 chapter 16 client system environment the client system environment is a collection of classes in the flash.System package that allow you to access system-level functionality such as determining which application and security domain a swf is executing in, determining the capabilities of the us...

  • Page 434

    434 client system environment getting data about the user’s system at runtime by checking the system.Totalmemory property, you can determine the amount of memory (in bytes) that flash player is currently using. This property allows you to monitor memory usage and optimize your applications based on ...

  • Page 435

    Capabilities class 435 capabilities class the capabilities class allows developers to determine the environment in which a swf file is being run. Using various properties of the capabilities class, you can find out the resolution of the user’s system, whether the user’s system supports accessibility...

  • Page 436

    436 client system environment applicationdomain class the purpose of the applicationdomain class is to store a table of actionscript 3.0 definitions. All code in a swf file is defined to exist in an application domain. You use application domains to partition classes that are in the same security do...

  • Page 437

    Applicationdomain class 437 } } } other things to keep in mind when you work with application domains include the following: ■ all code in a swf file is defined to exist in an application domain. The current domain is where your main application runs. The system domain contains all application domai...

  • Page 438

    438 client system environment the main application file is application1.Swf. It contains loader objects that load content from other swf files. In this scenario, the current domain is application domain 1. Usage a, usage b, and usage c illustrate different techniques for setting the appropriate appl...

  • Page 439

    Ime class 439 the following code creates a new child domain of the current domain: request.Url = "module3.Swf"; request.Applicationdomain = new applicationdomain(applicationdomain.Currentdomain); ime class the ime class lets you manipulate the operating system’s input method editor (ime) within flas...

  • Page 440

    440 client system environment checking if an ime is installed and enabled before you call any of the ime methods or properties, you should always check to see if the user’s computer currently has an ime installed and enabled. The following code illustrates how to check that the user has an ime both ...

  • Page 441

    Ime class 441 tf.Text = "current conversion mode is japananese hiragana."; break; case imeconversionmode.Japanese_katakana_full: tf.Text = "current conversion mode is japanese katakana (full- width)."; break; case imeconversionmode.Japanese_katakana_half: tf.Text = "current conversion mode is japane...

  • Page 442

    442 client system environment statustext.Text = "unable to set conversion mode." + error.Message; } } the previous code first creates a text field, which is used to display a status message to the user. Next, if the ime is installed, the code enables the ime and sets the conversion mode to korean....

  • Page 443

    Ime class 443 { if (capabilities.Hasime) { ime.Enabled = true; } } this example creates two input text fields, phonetxt and nametxt , and then adds two event listeners to the phonetxt text field. When the user sets focus to the phonetxt text field, a focusevent.Focus_in event is dispatched and the i...

  • Page 444

    444 client system environment outputtxt.Text = "unable to change ime."; } system.Ime.Addeventlistener(imeevent.Ime_composition, imecompositionhandler); } else { outputtxt.Text = "please install ime and try again."; } function imecompositionhandler(event:imeevent):void { outputtxt.Text = "you typed: ...

  • Page 445

    Example: detecting system capabilities 445 capabilitiesexplorer overview the capabilitiesexplorer.Mxml file is responsible for setting up the user interface for the capabilitiesexplorer application. The user’s flash player capabilities will be displayed within a datagrid component instance on the st...

  • Page 446

    446 client system environment } capdp.Sorton("name", array.Caseinsensitive); return capdp; } the getbrowserobjects() method returns an array of each of the propreties in the browser’s navigator object. If this array has a length of one or more items, the array of browser capabilities ( navarr ) is a...

  • Page 447

    Example: detecting system capabilities 447 communicating with javascript the final piece in building the capabilitiesexplorer application is writing the necessary javascript to loop over each of the items in the browser’s navigator object and append a name- value pair to a temporary array. The code ...

  • Page 448

    448 client system environment return temparr.Join("&"); } the code begins by creating a temporary array that will hold all the name-value pairs in the navigator object. Next, the navigator object is looped over using a for..In loop, and the data type of the current value is evaluated to filter out u...

  • Page 449

    449 17 chapter 17 flash player security security is a key concern of adobe, users, website owners, and content developers. For this reason, adobe flash player 9 includes a set of security rules and controls to safeguard the user, website owner, and content developer. This chapter discusses how to wo...

  • Page 450

    450 flash player security flash player security overview much of flash player security is based on the domain of origin for loaded swf files, media, and other assets. A swf file from a specific internet domain, such as www.Example.Com, can always access all data from that domain. These assets are pu...

  • Page 451

    Flash player security overview 451 in the flash player security model, there is a distinction between loading content and accessing or loading data . ■ loading content— content is defined as media, including visual media flash player can display, audio, video, or a swf file that includes displayed m...

  • Page 452

    452 flash player security overview of permission controls the flash player client run-time security model has been designed around resources, which are objects such as swf files, local data, and internet urls. Stakeholders are the parties who own or use those resources. Stakeholders can exercise con...

  • Page 453

    Overview of permission controls 453 the mms.Cfg file on mac os x systems, the mms.Cfg file is located at /library/application support/ macromedia/mms.Cfg. On microsoft windows systems, the file is located in the macromedia flash player folder in the system directory (for example, c:\windows\system32...

  • Page 454

    454 flash player security the global flash player trust directory administrative users and installer applications can register specified local swf files as trusted. These swf files are assigned to the local-trusted sandbox. They can interact with any other swf files, and they can load data from anyw...

  • Page 455

    Overview of permission controls 455 the settings ui and settings manager the settings ui is a quick, interactive mechanism for configuring the settings for a specific domain. The settings manager presents a more detailed interface and provides the ability to make global changes that affect permissio...

  • Page 456

    456 flash player security these settings affect only the current user, not other users who log in to the computer. If a user without administrative rights installs an application in their own portion of the system, the user flash player trust directory lets the installer register the application as ...

  • Page 457

    Overview of permission controls 457 when a swf file attempts to access data from another domain, flash player automatically attempts to load a policy file from that domain. If the domain of the swf file that is attempting to access the data is included in the policy file, the data is automatically a...

  • Page 458

    458 flash player security if data to be loaded is on a https server, but the swf file loading it is on an http server, adobe recommends that you move the loading swf file to an https server so that you can keep all copies of your secure data under the protection of https. However, if you decide that...

  • Page 459

    Overview of permission controls 459 when policy files were first introduced in flash player 6, there was no support for socket policy files. Connections to socket servers were authorized by a policy file from the default location of the cross-domain policy file on an http server on port 80 of the sa...

  • Page 460

    460 flash player security author (developer) controls the main actionscript api used to grant security privileges is the security.Allowdomain() method, which grant privileges to swf files in the domains that you specify. In the following example, a swf file grants access to swf files served from the...

  • Page 461

    Security sandboxes 461 another important security-related method is the security.Loadpolicyfile() method, which causes flash player to check for a cross-domain policy file at a nonstandard location. For more information, see “website controls (cross-domain policy files)” on page 456 . Security sandb...

  • Page 462

    462 flash player security local sandboxes local file describes any file that is referenced by using the file: protocol or a universal naming convention (unc) path. Local swf files are placed into one of three local sandboxes: ■ the local-with-filesystem sandbox—for security purposes, flash player pl...

  • Page 463

    Security sandboxes 463 swf files in the local-with-networking sandbox cannot load swf files in the local-with- filesystem sandbox. Swf files in the local-with-filesystem sandbox cannot load swf files in the local-with-networking sandbox. Setting the sandbox type of local swf files you can configure ...

  • Page 464

    464 flash player security restricting networking apis you can control a swf file’s access to network functionality by setting the allownetworking parameter in the and tags in the html page that contains the swf content. Possible values of allownetworking are: ■ "all" (the default)—all networking api...

  • Page 465

    Full-screen mode security 465 an addition to those apis on the previous list, the following apis are also prevented when allownetworking is set to "none" : ■ sendtourl() ■ filereference.Download() ■ filereference.Upload() ■ loader.Load() ■ localconnection.Connect() ■ localconnection.Send() ■ netconn...

  • Page 466

    466 flash player security to enable full-screen mode, in the and tags in the html page that contains a reference to the swf file, add the allowfullscreen parameter, with its value set to "true" (the default value is "false" ), as shown in the following example: codebase="http://fpdownload.Macromedia...

  • Page 467

    Loading content 467 loading content a swf file can load the following types of content: ■ swf files ■ images ■ sound ■ video loading swf files and images you use the loader class to load swf files and images (jpg, gif, or png files). Any swf file, other than one in the local-with-filesystem sandbox,...

  • Page 468

    468 flash player security when you call the load() method of the loader object, you can specify a context parameter, which is a loadercontext object. The loadercontext class includes three properties that let you define the context of how the loaded content can be used: ■ checkpolicyfile —use this p...

  • Page 469

    Loading content 469 an important property of a loader object is the contentloaderinfo property, which is a loaderinfo object. Unlike most other objects, a loaderinfo object is shared between the loading swf file and the loaded content, and it is always accessible to both parties. When the loaded con...

  • Page 470

    470 flash player security when you use an tag in a text field to load an external file (as opposed to using a bitmap class embedded within your swf), a loader object is automatically created as a child of the textfield object, and the external file is loaded into that loader just as if you had used ...

  • Page 471

    Cross-scripting 471 if two swf files written with actionscript 3.0 are served from different domains—for example, http://sitea.Com/swfa.Swf and http://siteb.Com/swfb.Swf—then, by default, flash player does not allow swfa.Swf to script swfb.Swf, nor swfb.Swf to script swfa.Swf. A swf file gives permi...

  • Page 472

    472 flash player security in addition to protecting swf files from cross-domain scripting originated by other swf files, flash player protects swf files from cross-domain scripting originated by html files. Html-to-swf scripting can occur with callbacks established through the externalinterface.Addc...

  • Page 473

    Cross-scripting 473 there are also restrictions on the removechildat() and swapchildrenat() methods of the stage object, but these are different from the other restrictions. Rather than needing to be in the same domain as the stage owner, to call these methods code must be in the same domain as the ...

  • Page 474

    474 flash player security for events that are dispatched from objects other than display objects, there are no security checks or security-related implications. Accessing loaded media as data you access loaded data using methods such as bitmapdata.Draw() and soundmixer.Computespectrum() . By default...

  • Page 475

    Accessing loaded media as data 475 when you load the image using the load() method of the loader class, you can specify a context parameter, which is a loadercontext object. If you set the checkpolicyfile property of the loadercontext object to true , flash player checks for a cross-domain policy fi...

  • Page 476

    476 flash player security you can use the soundmixer.Aresoundsinaccessible() method to find out whether a call to the soundmixer.Stopall() method would not stop all sounds because the sandbox of one or more sound owners is inaccessible to the caller. Calling the soundmixer.Stopall() method stops tho...

  • Page 477

    Loading data 477 loading data swf files can load data from servers into actionscript, and send data from actionscript to servers. Loading data is a different kind of operation from loading media, because the loaded information appears directly in actionscript, rather than being displayed as media. G...

  • Page 478

    478 flash player security to retrieve a socket policy file from the same port as a main socket connection, simply call the socket.Connect() or xmlsocket.Connect() method, and, if the specified domain is not the same as the domain of the calling swf file, flash player automatically attempts to retrie...

  • Page 479

    Loading embedded content from swf files imported into a security domain 479 uploading and downloading files the filereference.Upload() method starts the upload of a file selected by a user to a remote server. You must call the filereference.Browse() or filereferencelist.Browse() method before callin...

  • Page 480

    480 flash player security an alternative way for a swf file to access classes in loaded swf files from a different security sandbox is to have the loaded swf file call the security.Allowdomain() method to grant access to the domain of the calling swf file. You can add the call to the security.Allowd...

  • Page 481

    Controlling access to scripts in a host web page 481 setting localconnection permissions the localconnection class lets you develop swf files that can send instructions to each other. Localconnection objects can communicate only among swf files that are running on the same client computer, but they ...

  • Page 482

    482 flash player security set this parameter in the html code for the web page that hosts a swf file. You set the parameter in the param or embed tag. The allowscriptaccess parameter can have one of three possible values: "always" , "samedomain" , or "never" : ■ when allowscriptaccess is "samedomain...

  • Page 483

    Shared objects 483 shared objects flash player provides the ability to use shared objects , which are actionscript objects that persist outside of a swf file, either locally on a user’s file system or remotely on an rtmp server. Shared objects, like other media in flash player, are partitioned into ...

  • Page 484

    484 flash player security the choice of a shared object store is based on a swf file’s origin url. This is true even in the two situations where a swf file does not originate from a simple url: import loading and dynamic loading. Import loading refers to the situation where you load a swf file with ...

  • Page 485

    Camera, microphone, clipboard, mouse, and keyboard access 485 the system.Setclipboard() method allows a swf file to replace the contents of the clipboard with a plain-text string of characters. This poses no security risk. To protect against the risk posed by passwords and other sensitive data being...

  • Page 486

    486 flash player security.

  • Page 487

    487 18 chapter 18 printing adobe flash player 9 can communicate with an operating system’s printing interface so that you can pass pages to the print spooler. Each page flash player sends to the spooler can contain content that is visible, dynamic, or offscreen to the user, including database values...

  • Page 488

    488 printing what’s new for the printjob class using actionscript 3.0 the printjob class hasn’t changed dramatically for the actionscript 3.0 implementation of printing. However, a few critical differences are worth noting: ■ the printjob.Addpage() method now takes a sprite and a rectangle object fo...

  • Page 489

    Flash player tasks and system printing 489 so, for example, a very simple print job script may look like the following (including package , import and class statements for compiling): package { import flash.Printing.Printjob; import flash.Display.Sprite; public class basicprintexample extends sprite...

  • Page 490

    490 printing working with exceptions and returns you should check to see if the printjob.Start() method returns true before executing addpage() and send() calls, in case the user has cancelled the print job. A simple way to check whether these methods have been cancelled before continuing is to wrap...

  • Page 491

    Flash player tasks and system printing 491 if flash player encounters a problem sending the print job to the printer (for example, if the printer is offline), you can catch that exception, too, and provide the user (or flash player) with information or more options (such as displaying message text o...

  • Page 492

    492 printing setting vector or bitmap rendering you can manually set the print job to spool each page as vector graphics or a bitmap image. In some cases, vector printing will produce a smaller spool file, and a better image than bitmap printing. However, if your content includes a bitmap image, and...

  • Page 493

    Setting size, scale, and orientation 493 setting size, scale, and orientation the section “printing a page” on page 488 details the steps for a basic print job, where the output directly reflects the printed equivalent of the screen size and position of the specified sprite. However, printers use di...

  • Page 494

    494 printing comparing points and pixels a rectangle's width and height are pixel values. A printer uses points as print units of measurement. Points are a fixed physical size (1/72 inch), but the size of a pixel on the screen depends on the resolution of the particular screen. The conversion rate b...

  • Page 495

    Example: multiple-page printing 495 printing for landscape or portrait orientation because flash player can detect the settings for orientation, you can build logic into your actionscript to adjust the content size or rotation in response to the printer settings, as the following example illustrates...

  • Page 496

    496 printing import flash.Geom.Rectangle; public class printmultiplepages extends movieclip { private var sheet1:sprite; private var sheet2:sprite; public function printmultiplepages():void { init(); printpages(); } private function init():void { sheet1 = new sprite(); createsheet(sheet1, "once upon...

  • Page 497

    Example: multiple-page printing 497 { var pj:printjob = new printjob(); var pagestoprint:uint = 0; if (pj.Start()) { if (pj.Orientation == printjoborientation.Landscape) { throw new error("page is not set to an orientation of portrait."); } sheet1.Height = pj.Pageheight; sheet1.Width = pj.Pagewidth;...

  • Page 498

    498 printing example: scaling, cropping, and responding in some cases, you may want adjust the size (or other properties) of a display object when printing it to accommodate differences between the way it appears on screen and the way it appears printed on paper. When you adjust the properties of a ...

  • Page 499

    Example: scaling, cropping, and responding 499 trace(">> pj.Paperheight: " + pj.Paperheight); try { pj.Addpage(this, new rectangle(0, 0, 100, 100)); } catch (e:error) { // do nothing. } pj.Send(); } else { txt.Text = "print job canceled"; } // reset the txt scale properties. Txt.Scalex = 1; txt.Scal...

  • Page 500

    500 printing.

  • Page 501

    501 19 chapter 19 using the external api the actionscript 3.0 external api enables straightforward communication between actionscript and the container application within which adobe flash player 9 is running. There are several situations in which you may want to use the external api—for example, wh...

  • Page 502

    502 using the external api about the external api the external api is the portion of actionscript that provides a mechanism for communication between actionscript and code running in an “external application” that is acting as a container for flash player (commonly a web browser or stand-alone proje...

  • Page 503

    Using the externalinterface class 503 from actionscript, you can call a javascript function on the html page. The external api offers the following improved functionality compared with fscommand() : ■ you can use any javascript function, not only the functions that you can use with the fscommand() f...

  • Page 504

    504 using the external api getting information about the external container the externalinterface.Available property indicates whether the current flash player is in a container that offers an external interface. If the external interface is available, this property is true ; otherwise, it is false ...

  • Page 505

    Using the externalinterface class 505 if the container is an html page, this method invokes the javascript function with the specified name, which must be defined in a element in the containing html page. The return value of the javascript function is passed back to actionscript. // adds two numbers...

  • Page 506

    506 using the external api calling actionscript code from the container a container can only call actionscript code that’s in a function—no other actionscript code can be called by a container. To call an actionscript function from the container application, you must do two things: register the func...

  • Page 507

    Example: using the external api with a web page container 507 in either case, the return value of the actionscript function is passed back to the container code, either directly as a value when the caller is javascript code in a browser, or serialized as an xml-formatted string when the caller is an...

  • Page 508

    508 using the external api preparing for actionscript-browser communication one of the most common uses for the external api is to allow actionscript applications to communicate with a web browser. Using the external api, actionscript methods can call code written in javascript and vice versa. Becau...

  • Page 509

    Example: using the external api with a web page container 509 } } first of all, the code checks whether the external api is even available in the current container using the externalinterface.Available property. If so, it begins the process of setting up communication. Because security exceptions an...

  • Page 510

    510 using the external api back in the immanager constructor, one of two things happens depending on the readiness of the container. If iscontainerready() returns true , the code simply calls the setupcallbacks() method, which completes the process of setting up communication with javascript. On the...

  • Page 511

    Example: using the external api with a web page container 511 the setcallbacks() method finishes the task of preparing for communication with the container by calling externalinterface.Addcallback() to register the two methods that will be available to be called from javascript. In this code, the fi...

  • Page 512

    512 using the external api calling actionscript code from javascript communication is supposed to be a two-way street, and the introvert im application is no exception. Not only does the flash player im client call javascript to send messages, but the html form calls javascript code to send messages...

  • Page 513

    Example: using the external api with a web page container 513 ■ the getstatus() actionscript method returns a value, and that value is assigned to the currentstatus variable, which is then assigned as the content (the value property) of the status text field. The sendmessage() javascript function de...

  • Page 514

    514 using the external api detecting the browser type because of differences in how browsers access content, it’s important to always use javascript to detect which browser the user is running and to access the movie according to the browser- specific syntax, using the window or document object, as ...

  • Page 515

    Example: using the external api with an activex container 515 the introvert im c# files can be found in the samples/introvertim_csharp folder. The application consists of the following files: file description appform.Cs the main application file with the c# windows forms interface. Bin/debug/introve...

  • Page 516

    516 using the external api overview of the introvert im c# application this example application represents two instant-messaging client programs (one within a swf file and another built with windows forms) that communicate with each other. The user interface includes an instance of the shockwave® fl...

  • Page 517

    Example: using the external api with an activex container 517 understanding actionscript to activex container communication communication using the external api with an activex container application works like communication with a web browser, with one important difference. As described earlier, whe...

  • Page 518

    518 using the external api the application declares and creates an externalinterfaceproxy instance named proxy , passing in a reference to the shockwave flash activex control that is in the user interface ( introvertimapp ). Next, the code registers the proxy_externalinterfacecall() method to receiv...

  • Page 519

    Example: using the external api with an activex container 519 an externalinterfacecall instance is a simple value object with two properties. The functionname property contains the function name specified in the actionscript externalinterface.Call() statement. If any parameters are added in actionsc...

  • Page 520

    520 using the external api as this example shows, the externalinterfaceproxy class’s call() method is very similar to its actionscript counterpart, externalinterface.Call() . The first parameter is a string, the name of the function to call. Any additional parameters (not shown here) are passed alon...

  • Page 521

    Example: using the external api with an activex container 521 receiving a function call from actionscript is a multistep process. Function calls from actionscript cause the shockwave flash activex control to dispatch its flashcall event, so a class (such as the externalinterfaceproxy class) that int...

  • Page 522

    522 using the external api the external api’s xml format communication between actionscript and an application hosting the shockwave flash activex control uses a specific xml format to encode function calls and values. In the introvert im c# example, the externalinterfaceproxy class makes it possibl...

  • Page 523

    Example: using the external api with an activex container 523 individual values, including function parameters and function return values, use a formatting scheme that includes data type information in addition to the actual values: actionscript class/value c# class/ value format comments null null ...

  • Page 524

    524 using the external api.