Adobe FLEX 2-PROGRAMMING ACTIONSCRIPT 3.0 Manual
Adobe FLEX 2-PROGRAMMING ACTIONSCRIPT 3.0 Manual

Adobe FLEX 2-PROGRAMMING ACTIONSCRIPT 3.0 Manual

Programming actionscript 3.0
Table of Contents

Advertisement

Quick Links

Advertisement

Table of Contents
loading
Need help?

Need help?

Do you have a question about the FLEX 2-PROGRAMMING ACTIONSCRIPT 3.0 and is the answer not in the manual?

Questions and answers

Summary of Contents for Adobe FLEX 2-PROGRAMMING ACTIONSCRIPT 3.0

  • 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 with the terms of such license. Except as permitted by any such license, no part of this guide may be reproduced, stored in a retrieval system, or transmitted, in any form or by any means, electronic, mechanical, recording, or otherwise, without the prior written permission of Adobe Systems Incorporated.
  • Page 3: Table Of Contents

    Contents PART 1: OVERVIEW OF ACTIONSCRIPT PROGRAMMING About This Manual........11 Using this manual .
  • Page 4 Advanced topics ..........139 Example: GeometricShapes .
  • Page 5 Handling synchronous errors in an application ....261 Creating custom error classes ....... . 266 Responding to error events and status .
  • Page 6 flash.text package ..........342 flash.ui package .
  • Page 7 Loading content ..........467 Cross-scripting .
  • Page 8 Contents...
  • Page 9 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 ActionScript 3.0 .
  • Page 11: About This Manual

    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 understand basic object-oriented programming concepts like classes and inheritance.
  • Page 12: Using This Manual

    Using this manual This manual is divided into the following parts: Part Description Part 1, “Overview of ActionScript Discusses core ActionScript 3.0 concepts, Programming” including language syntax, statements and operators, the ECMAScript edition 4 draft language specification, object-oriented ActionScript programming, and the new approach to managing display objects on the Adobe Flash...
  • Page 13: Accessing Actionscript Documentation

    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 tools to learn how to use them to write and compile ActionScript 3.0 code.
  • Page 14: Developer Center

    Flex documentation If you use the Flex development environment, you may want to consult these manuals: Book Description Describes how to develop your dynamic web Flex 2 Developer’s Guide applications. Contains an overview of Flex features and Getting Started with Flex 2 application development procedures.
  • Page 15: Chapter 1: Introduction To Actionscript 3.0

    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............15 Advantages of ActionScript 3.0 .
  • Page 16: Advantages Of 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 native data type of the language.
  • Page 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 robustly. Run-time errors can provide stack traces annotated with source file and line number information, helping you quickly pinpoint errors.
  • Page 18 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 a native data type of the language.
  • Page 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 the World Wide Web Consortium DOM Level 3 Events Specification, this model provides a clearer and more efficient mechanism than the event systems available in previous versions of ActionScript.
  • Page 20: Compatibility With Previous Versions

    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 being downloaded. The ByteArray class lets you optimize reading, writing, and working with binary data.
  • Page 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 this through a call to , passing a value of 0 to the parameter.
  • Page 22 Introduction to ActionScript 3.0...
  • Page 23 ActionScript 3.0: Design your application. You should describe your application in some way before you start building it. Compose your ActionScript 3.0 code. You can create ActionScript code using Flash, Flex Builder, Macromedia Dreamweaver® from Adobe, or a text editor.
  • Page 24: Chapter 2: Getting Started With Actionscript

    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 Flex development environment, creating a new application file involves defining the application and adding user interface components using MXML, and referencing the ActionScript code.
  • Page 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 FLA files. However, in order to use the same code in another Flash or Flex project, you must copy and paste the code into the new file.
  • Page 26: Example: Creating A Basic Application

    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, methods, and events, just as you would with any of the built-in ActionScript classes.
  • Page 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 as complicated as a set of requirements documents containing numerous Unified Modeling Language (UML) diagrams.
  • Page 28 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 Adding code to the Greeter class The Greeter class defines an object, , that you will be able to use in your HelloWorld Greeter...
  • Page 29 To create an ActionScript application using Flex Builder: Open the HelloWorld.mxml file, and type the following code: <?xml version="1.0" encoding="utf-8"?> <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" xmlns="*" layout="vertical" creationComplete = "initApp()" > <mx:Script> <![CDATA[ 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();...
  • Page 30 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 design, and if it doesn’t, you edit the code again until it does.
  • Page 31 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"]; * Builds a greeting string using the given name. public function sayHello(userName:String = ""):String var greeting:String;...
  • Page 32 The Greeter class now has a number of new features: array lists valid user names. The array is initialized to a list of three validNames ■ names when the Greeter class is loaded. method now accepts a user name and changes the greeting based on sayHello() ■...
  • Page 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(); ]]> </mx:Script> <mx:TextArea id = "mainTxt" width="400" backgroundColor="#DDDDDD" editable="false" /> <mx:HBox width="400"> <mx:Label text="User Name:"/> <mx:TextInput id="userNameTxt" width="100%" enter="mainTxt.text = myGreeter.sayHello(userNameTxt.text);"...
  • Page 34 Getting Started with ActionScript...
  • Page 35: Chapter 3: Actionscript Language And Syntax

    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 specification. The Flash Player API provides programmatic access to Flash Player.
  • Page 36 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, the standard upon which ActionScript 3.0 is based, defines objects in a similar but slightly different way.
  • Page 37: Objects And Classes

    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 encapsulate behavior bound to the class.
  • Page 38: Packages And Namespaces

    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 as property and method names, and can be applied to code whether it resides inside or outside a package.
  • Page 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 advanced use of this feature is to define a namespace at the top level of a package so that it will be available to all classes in that package.
  • Page 40 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 in Part 3 of this book.
  • Page 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 this chapter. If the class resides in a package named samples, you must use one of the following import statements before using the SampleCode class: import samples.*;...
  • Page 42 When a package is created, the default access specifier for all members of that package is , which means that, by default, package members are only visible to other members internal of that package. If you want a class to be available to code outside the package, you must declare that class to be .
  • Page 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.samples.SampleCode(); Programmers with a C++ background often confuse the import statement with #include.
  • Page 44 There are three basic steps to follow when using namespaces. First, you must define the namespace using the keyword. For example, the following code defines the namespace namespace: version1 namespace version1; Second, you apply your namespace by using it instead of an access control specifier in a property or method declaration.
  • Page 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 namespace defined within the flash.utils flash_proxy package.
  • Page 46 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 ten different functions, you must add your namespace as an attribute to each of the ten function definitions.
  • Page 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 property from ActionScript 2.0, allows you to Object.__resolve intercept references to undefined properties or methods before an error occurs.
  • Page 48 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 an undefined method, such as the method called in the following example, your Proxy object intercepts the method testing() call and executes the statements inside the overridden method (in this case,...
  • Page 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 statement. use namespace This example uses four files to demonstrate the technique.
  • Page 50 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 file, NamespaceUseCase.as, is the main application class, and should be a sibling to the example folder.
  • Page 51: Variables

    Variables Variables allow you to store values that you use in your program. To declare a variable, you must use the statement with the variable name. In ActionScript 2.0, use of the statement is only required if you use type annotations. In ActionScript 3.0, use of the statement is always required.
  • Page 52 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;...
  • Page 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 code creates a global string variable named , and then creates a local variable of the same name str1...
  • Page 54 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 all variable declarations to the top of the function.
  • Page 55: Data Types

    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, int, and uint, the default value of any uninitialized variable is...
  • Page 56 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 for some operations and wrapper objects better suited for other operations.
  • Page 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. To associate a data type with a parameter, you use the colon operator followed by the data type.
  • Page 58 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 argument to a function that expects an array.
  • Page 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 type of a class instance, but a subclass to instantiate it.
  • Page 60 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 creates an instance of the Sprite class named and uses the operator to test whether...
  • Page 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 dynamic classes by using the attribute when you declare a class.
  • Page 62 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 class must be qualified with either the keyword or the class name. The Protean this following example shows the...
  • Page 63 Null data type The Null data type contains only one value, . This is the default value for the String data null 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 value null Flash Player will convert the value to the appropriate default value if you attempt to...
  • Page 64 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 ) to 9,007,199,254,740,992 (2 Flash Player uses the value not only as the default value for variables of type , but...
  • Page 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 type is no longer the default data type assigned to variables with no type annotation.
  • Page 66 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 ( ) operator ■...
  • Page 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 is assigned for the Number data type.
  • Page 68 In ActionScript 3.0, the function no longer supports octal, or base 8, numbers. If Number() you supply a string with a leading zero to the ActionScript 2.0 function, the Number() number is interpreted as an octal number, and converted to its decimal equivalent. This is not true with the function in ActionScript 3.0, which instead ignores the leading zero.
  • Page 69 Casting to Boolean Casting to Boolean from any of the numeric data types (uint, int, and Number) results in if the numeric value is 0, and otherwise. For the Number data type, the value false true also results in . The following example shows the results of casting the numbers -1, 0, false and 1: var myNum:Number;...
  • Page 70 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 all other data types, casting to Boolean is not necessary to avoid strict mode errors.
  • Page 71: Syntax

    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 = new Date(2005,6,1);...
  • Page 72 public function method1():void {} Using dot syntax, you can access the property and the method using the prop1 method1() instance name created in the following code: var myDotEx:DotExample = new DotExample(); myDotEx.prop1 = “hello”; myDotEx.method1(); You can use dot syntax when you define packages. You use the dot operator to refer to nested packages.
  • Page 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 statement and pass the compound literal as a parameter to the Array class constructor, but you can also assign literal values directly when instantiating instances of the following ActionScript core classes: Object, Array, String, Number, int, uint, XML, XMLList and Boolean.
  • Page 74 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 used to alter the order of operations in the following code: trace(2 + 3 * 4);...
  • Page 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 error if you use a lexical keyword as an identifier.
  • Page 76 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 use many of these identifiers in your code, but Adobe recommends that you do not use them because they may appear as keywords in a subsequent version of the language.
  • Page 77: Operators

    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 outside the class, a run-time error MAXIMUM will occur. class A public const MINIMUM:int = 0;...
  • Page 78 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 operands. If both operands are numbers, the addition operator returns the sum of the values.
  • Page 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 statements produce the same output: trace(3 >...
  • Page 80 Group Operators Additive Bitwise shift << >> >>> Relational < > <= >= as in instanceof is Equality == != === !== Bitwise AND & Bitwise XOR Bitwise OR Logical AND && Logical OR Conditional Assignment = *= /= %= += -= <<= >>= >>>= &= ^= |= Comma Primary operators The primary operators include those used for creating Array and Object literals, grouping...
  • Page 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 postfix operator is used as part of a larger expression, the expression’s value is returned before the postfix operator is processed.
  • Page 82 Operator Operation performed Deletes a property delete Returns type information typeof Returns undefined value void 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: Operator Operation performed Multiplication...
  • Page 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: Operator Operation performed Less than < Greater than > Less than or equal to <= Greater than or equal to >=...
  • Page 84 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: Operator Operation performed Logical AND && Logical OR Conditional operator The conditional operator is a ternary operator, which means that it takes three operands.
  • Page 85: Conditionals

    Conditionals ActionScript 3.0 provides three basic conditional statements that you can use to control program flow. if..else conditional statement allows you to test a condition and execute a block of if..else code if that condition exists, or execute an alternative block of code if the condition does not exist.
  • Page 86 if..else if You can test for more than one condition using the conditional statement. For if..else if example, the following code not only tests whether the value of exceeds 20, but also tests whether the value of is negative: if (x > 20) trace("x is >...
  • Page 87 switch statement is useful if you have several execution paths that depend on the same switch 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, statement evaluates an expression and uses the result to determine which block of switch code to execute.
  • Page 88: Looping

    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 only one statement, this practice is not recommended for the same reason that it is not recommended for conditionals: it increases the likelihood that statements added later will be inadvertently excluded from the block of code.
  • Page 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 properties that are added dynamically.
  • Page 90 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 the object is an instance of a sealed class.
  • Page 91: Functions

    } while (i < 5); // 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 the context in which the function is defined.
  • Page 92 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 functions with function statements if you prefer static, or strict mode, programming.
  • Page 93 An assignment statement with a function expression begins with the keyword, followed by: The function name ■ The colon operator ( ■ class to indicate the data type ■ Function The assignment operator ( ■ keyword function ■ The parameters, in a comma-delimited list enclosed in parentheses ■...
  • Page 94 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 function expression.
  • Page 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 garbage collection.
  • Page 96 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 defined only for subsequent statements. For example, the following code successfully calls the scopeTest() function before it is defined: statementTest();...
  • Page 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 functions inside function: getNameAndVersion() function getNameAndVersion():String...
  • Page 98 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 they were passed by value.
  • Page 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 parameter references the same object as the global variable. As you can objParam objVar see from the statements in the example, changes to the properties of the trace object are reflected in...
  • Page 100 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 aspect of the object to access any parameter passed to the function, whether or not that arguments parameter is defined in the function definition.
  • Page 101 You should also be careful to avoid using the string as a parameter name “arguments” because it will shadow the object. For example, if the function arguments traceArgArray() is rewritten so that an parameter is added, the references to in the arguments arguments function body refer to the parameter rather than the...
  • Page 102 // 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 function so that its traceArgArray() first parameter, , is of type int, and the second parameter uses the ...
  • Page 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 that stores the number of parameters defined for the function. This is length different from the property, which reports the number of arguments sent...
  • Page 104 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 the global scope is available throughout your code.
  • Page 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 retain information about the lexical environment in which they were created.
  • Page 106 ActionScript Language and Syntax...
  • Page 107: Classes

    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. Because of ActionScript’s roots as a scripting language, ActionScript 3.0 OOP support is optional.
  • Page 108: Chapter 4: 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 . ActionScript 3.0 not only continues to support class extends the keywords introduced in ActionScript 2.0, but also adds some new capabilities, such as enhanced access control with the attributes, and better control over protected...
  • Page 109: Classes

    public class BitmapData {} Class attributes ActionScript 3.0 allows you to modify class definitions using one of the following four attributes: Attribute Definition Allow properties to be added to instances at run time. dynamic Must not be extended by another class. final (default) Visible to references inside the current package.
  • Page 110 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 Accessibility public static function get active():Boolean;...
  • Page 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, including variables, constants, and methods. This differs from the way the term is used in the ActionScript 3.0 Language Reference, where the term is used more narrowly and includes only class members that are variables or are defined by a getter or setter method.
  • Page 112 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 was easily circumvented by using the property access operator ( ), which does the property lookup at run time rather than at compile time.
  • Page 113 Dynamic classes generally return the value instead of generating an error when undefined 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: Strict mode Standard mode...
  • Page 114 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. For more information, see “Static properties not inherited”...
  • Page 115 Code that is external to the StaticVars class and any of its subclasses can reference the properties only through the class itself. For example, the following totalCount MAX_NUM code works: trace(StaticVars.totalCount); // 0 trace(StaticVars.MAX_NUM); // 16 You cannot access static variables through an instance of the class, so the following code returns errors: var myStaticVars:StaticVars = new StaticVars();...
  • Page 116 Methods are defined using the keyword. You can use a function statement, such as function the following: public function sampleFunction():String {} Or you can use a variable to which you assign a function expression, as follows: public var sampleFunction:Function = function () {} In most cases you will want to use a function statement instead of a function expression for the following reasons: Function statements are more concise and easier to read.
  • Page 117 Constructor methods can only be public, but the use of the attribute is optional. You public cannot use any of the other access control specifiers, including , or private protected , on a constructor. You also cannot use a user-defined namespace with a constructor internal method.
  • Page 118 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 affects something other than the state of an individual instance.
  • Page 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 a static variable named to track the total number of class instances, arrayCountTotal...
  • Page 120 return this; var myTest:ThisTest = new ThisTest(); trace(myTest.thisValue() == myTest); // true Inheritance of instance methods can be controlled with the keywords override final You can use the attribute to redefine an inherited method, and the attribute override final to prevent subclasses from overriding a method. For more information, see “Overriding methods”...
  • Page 121 Instead, a user of the GetSet class will use something that appears to be a property named , but that is really a pair of get and set accessor functions that operate on the publicAccess private property named . The following example instantiates the GetSet privateProperty class, and then sets the value of the using the public accessor named...
  • Page 122 The following code defines a class named ThisTest, which contains a method named foo() that defines the bound method, and a method named that returns the bound method. bar() Code external to the class creates an instance of the ThisTest class, calls the method, bar() and stores the return value in a variable named...
  • Page 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 enumerations using classes and static constants.
  • Page 124 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 string or integer value. For example, the following code creates an enumeration class for the days of the week: public final class Day public static const MONDAY:Day = new Day();...
  • Page 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 method that returns a string representation of the day. You might toString() want to enhance the Day class in this manner as an exercise.
  • Page 126: Interfaces

    var sndChannel:SoundChannel = mySound.play(); To use the metadata tag in an Adobe Flex Builder 2 ActionScript project, you [Embed] must import any necessary classes from the Flex framework. For example, to embed sounds, you must import the mx.core.SoundAsset class. To use the Flex framework, include the file framework.swc in your ActionScript build path.
  • Page 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 class EventDispatcher implements IEventDispatcher function dispatchEvent(event:Event):Boolean /* implementation statements */...
  • Page 128 The Flash Player API follows a convention in which interface names begin with an uppercase , 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 be placed inside a class definition or inside another interface definition.
  • Page 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.
  • Page 130: Inheritance

    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 subclasses. A key advantage of inheritance is that it allows you to reuse code from a base class yet leave the existing code unmodified.
  • Page 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 guaranteed to possess all the properties of its base class, which means that an instance of a subclass can always be substituted for an instance of the base class.
  • Page 132 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 subclass is the MouseEvent class, which adds properties unique to events associated with mouse movement or mouse clicks, such as the events.
  • Page 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 named foo and the Extender class, which is a subclass of the Base class, is in a package named bar.
  • Page 134 To see how the other access control specifiers affect compilation and execution of the preceding example, change the variable’s access control specifier to private protected after deleting or commenting out the following line from the internal AccessControl class: trace (myExt.testString); // error if str is not public Overriding variables not permitted Properties that are declared with the...
  • Page 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 add to the behavior of the superclass method they are overriding instead of completely replacing the behavior.
  • Page 136 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.currentLabel; return str; The output of the statement in the OverrideExample class constructor is trace() Override: , which shows that the example was able to override the inherited null currentLabel...
  • Page 137 The only way to access the static variable is through the class object, as shown in the test 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 the static property or in a subclass.
  • Page 138 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 function Extender() trace(test); // output: static If an instance property is defined that uses the same name as a static property in the same class or a superclass, the instance property has higher precedence in the scope chain.
  • Page 139: Advanced Topics

    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) to perform significantly faster than previous versions of Flash Player that contain the old ActionScript Virtual Machine (AVM1).
  • Page 140 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 instances of that class. The following code creates a class named Shape and defines one property named that is visible...
  • Page 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: Object.prototype Shape.prototype Circle.prototype The base class at the end of every prototype chain is the Object class. The Object class contains a static property named that points to the base prototype object Object.prototype...
  • Page 142 ActionScript 2.0 ActionScript 2.0 introduced new keywords such as , and class extends public 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 understand that the underlying inheritance mechanism did not change between ActionScript 1.0 and ActionScript 2.0.
  • Page 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 that the class defines. ActionScript uses classes for both of these purposes, but its roots as a prototype-based language add an interesting characteristic.
  • Page 144 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 ActionScript 3.0, name lookup is much more efficient and less time consuming because inherited properties are copied down from superclasses into the traits object of subclasses.
  • Page 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 variable or method that is defined as part of a class definition. Fixed property inheritance is also called class inheritance because it is the inheritance mechanism that is associated with keywords such as , and...
  • Page 146 Unlike fixed property inheritance, however, prototype inheritance does not require the keyword if you want to redefine a method in a subclass. For example. if you want to override redefine the method in a subclass of the Object class, you have three options. valueOf() First, you can define a method on the subclass’s prototype object inside the class...
  • Page 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 4 draft language specification requires the use of prototype inheritance, which means that the properties and methods of a core class are defined on the prototype object of that class.
  • Page 148: Example: Geometricshapes

    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 compiler option represents the -as3 AS3 namespace, and the compiler option represents the prototype inheritance option ( stands for ECMAScript).
  • Page 149 File Description com/example/programmingas3/ A type of geometric shape that has sides of geometricshapes/RegularPolygon.as equal length postioned symmetrically around the shape’s center. com/example/programmingas3/ A type of geometric shape that defines a circle. geometricshapes/Circle.as com/example/programmingas3/ A subclass of RegularPolygon that defines a geometricshapes/EquilateralTriangle.as triangle with all sides the same length.
  • Page 150 The classes and interfaces that define the geometric shapes in this example are shown in the following diagram using Unified Modeling Language (UML) notation: GeometricShapes Example Classes << interface>> << interface>> IGeometricShape IPolygon +getArea (): Number +getPerimeter (): Number +describe(): String +getSumOfAngles (): Number Circle RegularPolygon...
  • Page 151 The interface defines two methods: the method, which calculates and returns the getArea() area of the shape, and the method, which assembles a text description of the describe() shape’s properties. We also want to know the distance around the perimeter of each shape. However, the perimeter of a circle is called the circumference and it’s calculated in a unique way, so the behavior diverges from that of a triangle or a square.
  • Page 152 // 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 Circle.\n"; desc += "Its diameter is "...
  • Page 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 return 0; public function describe():String var desc:String = "Each side is " + sideLength + " pixels long.\n"; desc += "Its area is "...
  • Page 154 The following code for the EquilateralTriangle class show how the method is getArea() overridden: package com.example.programmingas3.geometricshapes public class EquilateralTriangle extends RegularPolygon public function EquilateralTriangle(len:Number = 100):void super(len, 3); public override function getArea():Number // The formula is ((sideLength squared) * (square root of 3)) / 4. return ( (this.sideLength * this.sideLength) * Math.sqrt(3) ) / 4;...
  • Page 155 method also uses the statement, but in a different way—to invoke describe() super() the RegularPolygon superclass’ version of the method. The describe() method first sets the string variable to a statement EquilateralTriangle.describe() desc about the type of shape. Then it gets the results of the method RegularPolygon.describe() by calling...
  • Page 156 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 GeometricShapeFactory.currentShape = GeometricShapeFactory.createShape(shapeType, shapeSize); return GeometricShapeFactory.currentShape.describe(); factory method lets the shape subclass constructors define the details of createShape() the instances that they create, while returning the new objects as IGeometricShape instances so that they can be handled by the application in a more general way.
  • Page 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 methods. Then you would add a new Pentagon option to getArea() describe() the combo box in the application’s user interface.
  • Page 158 Object-Oriented Programming in ActionScript...
  • Page 159 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 visual elements. You’ll also learn about creating your own custom classes for display objects.
  • Page 160: Chapter 5: 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 groups: The Stage ■...
  • Page 161: Understanding The Display Architecture

    You can access the Stage through the property of any DisplayObject instance. For stage 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 display objects.
  • Page 162 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. AVM1Movie Bitmap InteractiveObject MorphShape Shape StaticText DisplayObjectContainer SimpleButton TextField Loader Sprite...
  • Page 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 “Drawing vector graphics” on page 176.
  • Page 164 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.
  • Page 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 the display object container.
  • Page 166 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 time to render these display objects. You can then add an off-list display object to the display list when it is needed.
  • Page 167: Working With Display Objects

    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.0. Properties and methods of the DisplayObject class All display objects are subclasses of the DisplayObject class, and as such they inherit the properties and methods of the DisplayObject class.
  • Page 168 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 through ActionScript.
  • Page 169 myTextField.text = "hello"; this.root.addChild(myTextField); In this code sample, points to the MovieClip display object container that this.root contains the code. In your actual code, you may specify a different container. Use the method to add the child to a specific position in the child list of the addChildAt() display object container.
  • Page 170 You can use the 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 getChildAt() pass it. For example, the following code reveals names of display objects at different positions in the child list of the DisplayObjectContainer object: container...
  • Page 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 the top of the tree is the Stage, which can contain multiple display objects.
  • Page 172 var url:URLRequest = new URLRequest("banana.jpg"); pict.load(url); pict.name = "banana loader"; container.addChild(title); container.addChild(pict); method returns the child of the display list at a specific index position: getChildAt() trace(container.getChildAt(0) is TextField); // true You can also access child objects by name. Each display object has a name property, and if you don’t assign it, Flash Player assigns a default value, such as .
  • Page 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 method addChild() and other methods of the DisplayObjectContainer class (which the Container class extends).
  • Page 174 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 the same as under normal mode; the scaling is controlled by the Stage class’s property.
  • Page 175 <object> <param name="allowFullScreen" value="true" /> <embed ... allowfullscreen="true" /> </object> 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 function (which is used by both Flex AC_FL_RunContent() Builder- and Flash-generated HTML pages) you should add the allowFullScreen...
  • Page 176: Basics For Working With The Core Display Classes

    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 , Flash Player dispatches an event object from the Stage child1 through the display list hierarchy down to the display object.
  • Page 177 The Graphics class includes the following methods for easily drawing simple shapes: , and drawCircle() drawEllipse() drawRect() drawRoundRect() . Before calling drawing methods, define the line style, fill, or both drawRoundRectComplex() by calling the linestyle() lineGradientStyle() beginFill() beginGradientFill() method. beginBitmapFill() Use the Sprite class if you want to create a graphical object that is also a display object container (to contain other display objects) but that does not require a timeline.
  • Page 178 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 created in the Flash authoring tool.
  • Page 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 image file—This includes JPG, PNG, and GIF files. ■...
  • Page 180 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 property of the Loader object.
  • Page 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: Stage LoaderInfo object Instance of property loaderInfo the main class of the SWF file...
  • Page 182 —Use this property only when loading a SWF file (not an image). ■ securityDomain 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 file, and if one exists, SWF files from the domains permitted in the cross- policy file can cross-script the loaded SWF content.
  • Page 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 MovieClip class are present as properties or methods of the ActionScript 3.0 MovieClip class.
  • Page 184 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 property that is a BitmapData object.
  • Page 185: Basics For Working With The Core Display Classes

    upState = new TextButtonState(0xFFFFFF, txt); downState = new TextButtonState(0xCCCCCC, txt); hitTestState = upState; overState = upState; addEventListener(MouseEvent.CLICK, buttonClicked); public function buttonClicked(e:Event) trace("Button clicked."); property of a SimpleButton object is a DisplayObject instance that hitTestState responds to the mouse events for the button. In this example, we set the hitTestState property (and the property) to be the same DisplayObject instance as the...
  • Page 186 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 method. attachCamera() Here is a simple example that attaches a net stream to a video and adds the video to the Sprite display object container: import flash.display.Sprite;...
  • Page 187: Example: Spritearranger

    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 with display objects: Extending display object classes ■...
  • Page 188 File Description com/example/programmingas3/ A subclass of RegularPolygon that defines a triangle geometricshapes/EquilateralTriangle.as with all sides the same length. com/example/programmingas3/ A subclass of RegularPolygon defining a rectangle geometricshapes/Square.as with all four sides the same length. com/example/programmingas3/ A class containing a “factory method” for creating geometricshapes/ shapes given a shape type and size.
  • Page 189 AS the following example shows, the method defines various properties of the initCanvas() DrawingCanvas object, which were passed as arguments to the constructor function: this.lineColor = lineColor; this.fillColor = fillColor; this.width = 500; this.height = 200; method then calls the method, which draws the canvas initCanvas() drawBounds()
  • Page 190 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.Sprite class: public class GeometricSprite extends Sprite The GeometricSprite class includes a number of properties common to all GeometricSprite objects.
  • Page 191 Adding display objects to the canvas When the user clicks the Add Shape button, the application calls the method of addShape() the DrawingCanvas class. It instantiates a new GeometricSprite by calling the appropriate constructor function of one of the GeometricSprite subclasses, as the following example shows: public function addShape(shapeName:String, len:Number):void var newShape:GeometricSprite;...
  • Page 192 The interface for the application includes two text fields, selectedSpriteTxt . The text properties of these text fields are updated with information about the outputTxt GeometricSprite objects that have been added to the canvas or selected by the user. The GeometricSprite class handles this information-reporting task by overriding the toString() method, as follows:...
  • Page 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 method is called, the method simply sets the onMouseDown() shape’s property (inherited from the DisplayObject class), as selectionIndicator visible follows: this.selectionIndicator.visible = true; method hides the shape of the previously hideSelected()
  • Page 194 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: moveToBack() moveDown() , or...
  • Page 195 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 ....197 Chapter 7: Working with Strings .
  • Page 197 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 and the new Timer class in the flash.utils package.
  • Page 198: Chapter 6: Working With Dates And Times

    Second, if given a single numeric parameter, the constructor treats that as the number Date() 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, in UTC. However, the Date object shows values in your local time zone, unless you use the UTC- specific methods to retrieve and display them.
  • Page 199: Managing Calendar Dates And Times

    property, which is the day of the week in numeric format, with 0 standing for ■ Sunday property, in the range of 0 to 23 ■ hours property minutes ■ property ■ seconds property milliseconds ■ In fact, the Date class gives you a number of ways to get each of these values. For example, you can get the month value of a Date object in four different ways: property month...
  • Page 200 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 methods: getTime() setTime() var oneHourFromNow:Date = new Date(); oneHourFromNow.setTime(oneHourFromNow.getTime() + millisecondsPerHour); Another way to set a date value is to create a new Date object using a single milliseconds parameter.
  • Page 201: Controlling Time Intervals

    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 mechanisms. Loops versus timers In some programming languages, you must devise your own timing schemes using loop statements like do..while.
  • Page 202 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 Timer var minuteTimer:Timer = new Timer(1000, 5); // designates listeners for the interval and completion events minuteTimer.addEventListener(TimerEvent.TIMER, onTick);...
  • Page 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 timing functions similar to those that were available in ActionScript 2.0.
  • Page 204 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 application ■...
  • Page 205: Example: Simple Analog Clock

    The class has two important properties: property, which is an instance of the AnalogClockFace class ■ The face property, which is an instance of the Timer class The ticker ■ The SimpleClock class uses a default constructor. The method takes care of the initClock() real setup work, creating the clock face and starting the Timer instance ticking.
  • Page 206 Starting the timer After creating the clock face, the method sets up a timer: initClock() // 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.TIMER, onTick); // starts the clock ticking ticker.start();...
  • Page 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 method to display the hands, as the showTime() following shows: * Displays the given Date/Time in that good old analog clock style. public function showTime(time:Date):void // gets the time values var seconds:uint = time.getSeconds();...
  • Page 208 Working with Dates and Times...
  • Page 209: Chapter 7: Working With Strings

    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, and FileReference objects.
  • Page 210: Chapter 7: 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 quotation mark ) delimiters, use the backslash escape character ( ).
  • Page 211: The Length Property

    Every string has a property, which is equal to the number of characters in the string: length 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: var str1:String = new String();...
  • Page 212: Comparing Strings

    You can also use character codes to define a string using the method, as the fromCharCode() 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 following operators to compare strings: , and >.
  • Page 213: Obtaining String Representations Of Other Objects

    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 operator with a combination of String objects and objects that are not strings, you do not need to use the method.
  • Page 214: Finding Substrings And Patterns In 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

    method functions similarly to the method. When given two non- slice() substring() negative integers as parameters, it works exactly the same. However, the method can slice() take negative integers as parameters, in which case the character position is taken from the end of the string, as shown in the following example: var str:String = "Hello from Paris, Texas!!!";...
  • Page 216 Creating an array of substrings segmented by a delimiter You can use the method to create an array of substrings, which is divided based on a split() delimiter. For example, you can segment a comma-delimited or tab-delimited string into multiple strings. The following example shows how to split an array into substrings with the ampersand (&) character as the delimiter: var queryStr:String = "first=joe&last=cheng&title=manager&StartDate=3/6/...
  • Page 217 Finding matching substrings method returns the index position of the first substring that matches a given search() pattern, as shown in this example: var str:String = "The more the merrier."; trace(str.search("the")); // output: 9 // (This search is case-sensitive.) You can also use regular expressions to define the pattern to match, as this example shows: var pattern:RegExp = /the/i;...
  • Page 218 Replacing matched substrings You can use the method to search for a specified pattern in a string and replace replace() matches with the specified replacement string, as the following example shows: var str:String = "She sells seashells by the seashore."; var pattern:RegExp = /sh/gi;...
  • Page 219: Converting Strings Between Uppercase And Lowercase

    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 euroSymbol:String = String.fromCharCode(8364); return euro.toFixed(2) + " " + euroSymbol; When you use a function as the second parameter of the method, the following replace() arguments are passed to the function:...
  • Page 220: Example: Ascii Art

    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: method of the String class is used to extract values from a character- ■ split() delimited string (image information in a tab-delimited text file). Several string-manipulation techniques, including , concatenation, and extracting ■...
  • Page 221: Example: Ascii Art

    The ASCIIArt application files can be found in the folder Samples/AsciiArt. The application consists of the following files: File Description AsciiArtApp.mxml The user interface for the application in MXML for Flex. com/example/programmingas3/asciiArt/ The class that provides the main functionality of AsciiArtBuilder.as the application, including extracting image metadata from a text file, loading the images,...
  • Page 222 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. ■...
  • Page 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 English titles).
  • Page 224 As its name suggests, the method actually does the work of capitalizeFirstLetter() 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 function capitalizeFirstLetter(word:String):String switch (word) case "and":...
  • Page 225 The remaining characters of the original word are extracted using , which substring(1) 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 method). substring() The final word is created by combining the newly capitalized first letter with the remaining letters using string concatenation: firstLetter + otherLetters...
  • Page 226 This code first defines a String instance named that will be used to build up the result 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 converts the red, green, and blue color values of an individual pixel to a single grayscale value (a number from 0 to 255).
  • Page 227: Indexed Arrays

    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, containing elements that are themselves arrays.
  • Page 228: Chapter 8: 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 arrays. Indexed arrays use an unsigned 32-bit integer for the index number. The maximum size of an indexed array is 2 -1 or 4,294,967,295.
  • Page 229: Indexed Arrays

    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(names.length);...
  • Page 230 Removing array elements Three methods of the Array class— , and —allow you to remove pop() shift() splice() elements from an array. The method removes an element from the end of the array. In pop() other words, it removes the element at the highest index number. The method shift() removes an element from the beginning of the array, which means that it always removes the...
  • Page 231 trace(oceans[2]); // output: undefined trace(oceans.length); // output: 5 You can truncate an array using an array’s property. If you set the property of length length an array to a length that is less than the current length of the array, the array is truncated, removing any elements stored at index numbers higher than the new value of minus length...
  • Page 232 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 method has an parameter that allows you to alter each sort() options characteristic of the default sort order.
  • Page 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 uses a regular expression to extract the last name orderLastName() from each element to use for the comparison operation. The function identifier is used as the sole parameter when calling the method on the orderLastName...
  • Page 234 trace(poets[i].name, poets[i].born); /* output: Wang 701 Dante 1265 Blake 1757 cummings 1894 Angelou 1928 Generally, the methods modify an array. If you wish to sort an array sort() sortOn() without modifying the existing array, pass the constant as part Array.RETURNINDEXEDARRAY of the parameter.
  • Page 235 Querying an array The remaining four methods of the Array class— concat() join() slice() —all query the array for information, but do not modify the array. The toString() methods both return new arrays, while the concat() slice() join() toString() methods both return strings. The method takes a new array or list of elements as concat() arguments and combines it with the existing array to create a new array.
  • Page 236: Associative Arrays

    One issue to be aware of with the method is that any nested arrays are always returned join() 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 = ["a",nested,"e"];...
  • Page 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 ratio"] = "16:10";...
  • Page 238 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 . The values can be GroupA GroupB of any data type, but in this example both are instances of the Object GroupA GroupB...
  • Page 239 Use the loop for direct access to the object keys of a Dictionary object. You can also for..in access the values of the Dictionary object with the property access ( ) operator. The following code uses the previous example of the dictionary to show how to iterate groupMap through a Dictionary object with the...
  • Page 240: Multidimensional Arrays

    If you use as a key in a Dictionary object, you are creating another reference to the myObject original object. For example, the following code creates two references to an object—the variable, and the key in the object: myObject myMap import flash.utils.Dictionary;...
  • Page 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 multidimensional array uses two indexed arrays to track task lists for each day of the week.
  • Page 242 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 day of the week, but at the cost of extra run time processing to access each element of the associative array.
  • Page 243: Cloning Arrays

    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 methods with no arguments. In a concat() slice() shallow copy, if the original array has elements that are objects, only the references to the objects are copied rather than the objects themselves.
  • Page 244 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 data type specified in the first parameter.
  • Page 245 The four overridden methods all use the AS3 namespace instead of the attribute public because this example assumes that the compiler option is set to and the compiler -as3 true option is set to . These are the default settings for Adobe Flex Builder 2 and for false Adobe Flash CS3 Professional.
  • Page 246 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, the data type passed to the constructor is assigned to the variable.
  • Page 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. Subsequently, each method calls the superclass version of itself.
  • Page 248 method takes an arbitrary list of arguments, but the first two arguments always splice() refer to an index number and the number of elements to delete. This is why the overridden method does type checking only for array elements in index positions 2 or splice() args higher.
  • Page 249: Example: Playlist

    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 objects by different properties, using different sorting options ■...
  • Page 250 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 Array();...
  • Page 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 of sorting the list of songs has three parts: identifying the property by which the list should be sorted, indicating what sorting options need to be used when sorting by that property, and performing the actual sort operation.
  • Page 252 Sorting by property and specifying sort options The work of actually sorting the list of songs is performed by the PlayList class in the method, as follows: sortList() * Sorts the list of songs according to the specified property. public function sortList(sortProperty:SortProperty):void var sortOptions:uint;...
  • Page 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.
  • Page 254 Working with Arrays...
  • Page 255 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 the error is encountered, as opposed to no response and whatever process created the error failing silently.
  • Page 256: Chapter 9: 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 errors occur when syntactical problems in your code prevent your application from being built.
  • Page 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 error event listener to wait for the application or user to try some operation, and if the operation fails, you catch the error with an event listener and respond to the error event.
  • Page 258: Error Handling In Actionscript 3.0

    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 statement or event handler can be found at the current or higher level to handle the catch error, the error is considered an uncaught exception.
  • Page 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 classes to expand the scope of situations that may produce error objects.
  • Page 260: Working With The Debugger Version Of Flash Player

    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 users will never know why your application fails when it does.
  • Page 261: Handling Synchronous Errors In An Application

    tf.text = error.toString(); If the method threw an EOFError in the debugger version of Flash Player, readBoolean() the following message would be displayed in the text field: “EOFError: Error #2030: End of file was encountered.” The same code in a release version of Flash Player would display the following text: “EOFError: Error #2030.”...
  • Page 262 statement encloses statements that will execute whether or not an error occurs finally in the block. If there is no error, the statements within the block execute after finally block statements complete. If there is an error, the appropriate statement catch executes first, followed by the statements in the block.
  • Page 263 throw new ArgumentError("I am an ArgumentError"); catch (error:ArgumentError) trace("<ArgumentError> " + error.message); catch (error:Error) trace("<Error> " + error.message); Several methods and properties in the Flash Player API throw run-time errors if they encounter errors while they execute. For example, the method in the Sound class close() throws an IOError if the method is unable to close the audio stream, as demonstrated in the...
  • Page 264 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(); // Perform any necessary cleanup here. Notice that the statements are ordered so that the most specific data types are listed catch...
  • Page 265 <costCenter>1-234</costCenter> </EmpCode>; public function SimpleError() 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(); errorMessage.autoSize = TextFieldAutoSize.LEFT; errorMessage.textColor = 0xFF0000; errorMessage.text = error.message; addChild(errorMessage); Using a wider range of error classes and built-in compiler errors, ActionScript 3.0 offers more information than previous versions of ActionScript about why something has failed.
  • Page 266: Creating Custom Error Classes

    catch (error:Error) trace("<< Error >> " + error); catch (error:ApplicationError) trace("<< catch >> " + error); The output from the previous snippet would be the following: << try >> << catch >> ApplicationError: some error which will be rethrown << throw >> <<...
  • Page 267: Responding To Error Events And Status

    The following shows an example of using AppError in your project: throw new AppError("Encountered Custom AppError", 29); catch (error:AppError) trace(error.errorID + ": " + error.message) If you want to override the method in your subclass, you need to give it Error.toString() (rest) parameter.
  • Page 268 Status-based error events ■ The status-based error events are related to the properties of the netStatus status networking and communication classes. If Flash Player encounters a problem when reading or writing data, the value of the netStatus.info.level status.level properties (depending on the class object you’re using) is set to the value .
  • Page 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(linkEvent.text); // your error handling code here private function errorHandler(errorEvent:IOErrorEvent):void trace(errorEvent.text); // your error handling code here Working with status change events Flash Player dynamically changes the value of the netStatus.info.level status.level properties for the classes that support the...
  • Page 270 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, netStatusHandler); connection.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler); connection.connect(null); private function netStatusHandler(event:NetStatusEvent):void if (event.info.level = "error") trace("Video stream failed") else connectStream(); private function securityErrorHandler(event:SecurityErrorEvent):void trace("securityErrorHandler: "...
  • Page 271: Comparing The Error Classes

    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: ActionScript core Error classes and flash.error package Error classes.
  • Page 272 Class name Description Notes ReferenceError A ReferenceError exception is Exceptions for undefined variables point thrown when a reference to an to potential bugs, helping you improve undefined property is attempted software quality. However, if you are not on a sealed (nondynamic) object. used to having to initialize your variables, Versions of the ActionScript this new ActionScript behavior may...
  • Page 273 Class name Description Notes TypeError The TypeError exception is A TypeError can be thrown under the thrown when the actual type of following circumstances: an operand is different from the • An actual parameter of a function or method could not be coerced to the expected type.
  • Page 274 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 edition 4 draft language specification that could potentially be interesting additions to the draft specification, they are kept at the top level instead of being placed in a package like flash.error.
  • Page 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. Class name Description Notes EOFError...
  • Page 276 Class name Description Notes MemoryError A MemoryError exception is By default, ActionScript Virtual thrown when a memory Machine 2 does not impose a limit allocation request fails. on how much memory an ActionScript program may allocate. On a desktop PC, memory allocation failures are infrequent.
  • Page 277: Example: Customerrors Application

    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 users when an error is thrown ■...
  • Page 278 </employee>; 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 method is called. This validateData() method validates the employee XML packet using the method in...
  • Page 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 TextArea component instance xmlText Button component instance are disabled, as the following code shows: validateBtn public function showFatalError(error:FatalError):void var message:String = error.message + "\n\n"...
  • Page 280 Building a custom validator The custom Validator class contains a single method, . The validateEmployeeXML() method takes a single argument, , which is the XML validateEmployeeXML() employee packet that you wish to validate. The method is as follows: validateEmployeeXML() public static function validateEmployeeXML(employee:XML):void // checks for the integrity of items in the XML if (employee.costCenter.length() <...
  • Page 281 The ApplicationError class’s constructor method is as follows: public function ApplicationError() messages = <errors> <error code="9000"> <![CDATA[Employee must be assigned to a cost center.]]> </error> <error code="9001"> <![CDATA[Employee must be assigned to only one cost center.]]> </error> <error code="9002"> <![CDATA[Employee must have one and only one SSN.]]> </error>...
  • Page 282 The final method in the ApplicationError class is This method overrides the toString(). 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 occurred.
  • Page 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 ApplicationError.FATAL, as seen in the following code: public function WarningError(errorID:int) id = errorID;...
  • Page 284 Handling Errors...
  • Page 285 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 expression matches a string that starts with the character A followed by one or more sequential digits: /A\d+/ Regular expression patterns can be complex, and sometimes cryptic in appearance, such as the...
  • Page 286: Chapter 10: 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 digits) or to replace portions of a text value which match a particular pattern.
  • Page 287: Regular Expression Syntax

    trace(str.match(pattern)); // 337,4, 57, 33 The following methods of the String class take regular expressions as parameters: match() , and . For more information on these methods, see “Finding replace() search() split() patterns in strings and replacing substrings” on page 216.
  • Page 288 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 constructor.
  • Page 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 the metacharacters that you can use in regular expressions: Metacharacter Description ^ (caret)
  • Page 290 Metacharacter Description [ and ] Defines a character class, which defines possible matches for a single character: /[aeiou]/ matches any one of the specified characters. Within character classes, use the hyphen (-) to designate a range of characters: /[A-Z0-9]/ matches uppercase A through Z or 0 through 9. Within character classes, insert a backslash to escape the ] and - characters: matches either...
  • Page 291 Metasequence Description Matches any white-space character (a space, tab, newline, or return character). Matches any character other than a white-space character. Matches the tab character. Matches the Unicode character with the character code specified by the \unnnn hexidecimal number . For example, is the smiley character.
  • Page 292 However, the three characters listed in the following table do function as metacharacters, with special meaning, in character classes: Metacharacter Meaning in character classes Defines the end of the character class. Defines a range of characters (see “Ranges of characters in character classes”...
  • Page 293 You can also use the ASCII character code to specify a range by ASCII value. For \xnn example, the following character class matches any character from a set of extended ASCII characters (such as é ê /[\x80-\x9A]/ Negated character classes When you use a caret ( ) character at the beginning of a character class, it negates that class—...
  • Page 294 You can use quantifiers within parenthetical groupings that have quantifiers applied to them. For example, the following quantifier matches strings such as word word-word-word /\w+(-\w+)*/ By default, regular expressions perform what is known as greedy matching. Any subpattern in the regular expression (such as ) tries to match as many characters in the string as possible before moving forward to the next part of the regular expression.
  • Page 295 Alternation Use the (bar) character in a regular expression to have the regular expression engine consider alternatives for a match. For example, the following regular expression matches any one of the words cat, dog, pig, rat var pattern:RegExp = /cat|dog|pig|rat/; You can use parentheses to define groups to restrict the scope of the | alternator.
  • Page 296 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 pattern = /a\d+/;...
  • Page 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.
  • Page 298 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. to define a positive lookahead group, which specifies that the subpattern in the group must match at the position. However, the portion of the string that matches the positive lookahead group can match remaining patterns in the regular expression.
  • Page 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. Flag Property Description Matches more than one match. global Case-insensitive matching. Applies to the —...
  • Page 300 When the flag is set, the method returns multiple matches, as follows: Sting.match() 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,shells,shore The i (ignoreCase) flag By default, regular expression matches are case-sensitive.
  • Page 301 Note that only the character signals the end of a line. The following characters do not: Return ( ) character ■ Unicode line-separator ( ) character \u2028 ■ Unicode paragraph-separator ( ) character ■ \u2029 The s (dotall) flag If the or “dot all”) flag is not set, a dot ( ) in a regular expression pattern does not dotall...
  • Page 302 The lastIndex property property specifies the index position in the string at which to start the next lastIndex search. This property affects the methods called on a regular expression exec() test() that has the flag set to . For example, consider the following code: true var pattern:RegExp = /p\w*/gi;...
  • Page 303: Methods For Using Regular Expressions With Strings

    Methods for using regular expressions with strings The RegExp class includes two methods: exec() test() In addition to the methods of the RegExp class, the String class includes exec() test() the following methods that let you match regular expressions in strings: match() replace() , and...
  • Page 304: Example: A Wiki Parser

    trace(result.index, "\t", pattern.lastIndex, "\t", result); result = pattern.exec(str); //output: // 0 // 10 seashells // 27 seashore String methods that use RegExp parameters The following methods of the String class take regular expressions as parameters: match() , and . For more information on these methods, see “Finding replace() search()
  • Page 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 string conversion. The constructor function, along with the method, simply initializes a sample setWikiData()
  • Page 306 The parentheses in the regular expression define a capturing group, and the replace() method refers to this group by using the code in the replacement string. The global flag in the regular expression ensures that the method replaces all matches in the replace() string (not simply the first one).
  • Page 307 symbols the regular expression match the beginning and end of a line. The ) flag in the regular expression causes the regular expression to match the ^ multiline symbol against the start of a line, not simply the start of the string. method replaces all matching substrings (empty lines) with an empty string replace() ).
  • Page 308 The call to the method employs the regular expression and assembles the replace() replacement HTML string, using backreferences. method then calls the method, which uses similar urlToATag() emailToATag() techniques to replace e-mail patterns with HTML hyperlink strings. The regular <a> expressions used to match HTTP, FTP, and e-mail URLs in this sample file are fairly simple, for the purposes of exemplification;...
  • Page 309 const euroSymbol:String = String.fromCharCode(8364); // € return euro.toFixed(2) + " " + euroSymbol; Note that represents the captured parenthetical group matched by the args[1] usdPrice regular expression. This is the numerical portion of the U.S. dollar string: that is, the dollar amount without the sign.
  • Page 310 Using Regular Expressions...
  • Page 311 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 faster than was possible with previous programming techniques.
  • Page 312: Chapter 11: 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 following XML document: <order xmlns = "http://www.example.com/xml">...
  • Page 313: The E4X Approach To Xml Processing

    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 example, an Adobe Flash Player 9 application and an application on a web server)—through a common standard such as the Simple Object Access Protocol (SOAP).
  • Page 314 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 attribute identifier ( ) operators, for accessing properties and attributes in the XML:...
  • Page 315: Xml Objects

    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 object is said to have simple content if it is any one of the following: an attribute, a comment, a processing instruction, or a text node.
  • Page 316 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() ■ insertChildAfter() ■...
  • Page 317: Xmllist Objects

    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: ■ defaultSettings() setSettings() ■...
  • Page 318 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 certain types of XML content: comments() ■...
  • Page 319: Initializing Xml Variables

    Initializing XML variables You can assign an XML literal to an XML object, as follows: var myXML:XML = <order> <item id='1'> <menuName>burger</menuName> <price>3.95</price> </item> <item id='2'> <menuName>fries</menuName> <price>1.45</price> </item> </order> As the following snippet shows, you can also use the constructor to create an instance of an XML object from a string that contains XML data: var str:String = "<order><item id='1'><menuName>burger</menuName>"...
  • Page 320: Assembling And Transforming Xml Objects

    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 information, see the XMLSocket entry in the ActionScript 3.0 Language Reference. Assembling and transforming XML objects Use the...
  • Page 321 As the following example shows, you can also use curly brace operators ( ) 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"], ["Smith","Vijay"]] var x:XML = new XML("<employeeList></employeeList>"); for (var i:int = 0;...
  • Page 322: Traversing Xml Structures

    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 a run-time error if the XML data is not well formed).
  • Page 323: Traversing Xml Structures

    Accessing parent and child nodes method returns the parent of an XML object. parent() You can use the ordinal index values of a child list to access specific child objects. For example, consider an XML object that has two child properties named .
  • Page 324 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 = <employee id="6401" code="233"> <lastName>Wu</lastName> <firstName>Erin</firstName> </employee>; trace(employee.@id); // 6401 You can use the wildcard symbol with the symbol to access all attributes of an XML or XMLList object, as in the following code:...
  • Page 325 Filtering by attribute or element value You can use the parentheses operators— —to filter elements with a specific element name or attribute value. Consider the following XML object: var x:XML = <employeeList> <employee id="347"> <lastName>Zmed</lastName> <firstName>Sue</firstName> <position>Data analyst</position> </employee> <employee id="348"> <lastName>McGee</lastName>...
  • Page 326 Similarly, the final line of following code generates an error because there is no property of the second element: var doc:XML = <body> <p id='123'>Hello, <b>Bob</b>.</p> <p>Hello.</p> </body>; trace(doc.p.(b == 'Bob')); To avoid these errors, you can identify the properties that have the matching attributes or elements by using the methods, as in the following code: attribute()
  • Page 327: Using Xml Namespaces

    statement lets you iterate over a set of property names in an XMLList: for..in var total:Number = 0; for (var pname:String in myXML.item) total += myXML.item.@quantity[pname] * myXML.item.price[pname]; statement lets you iterate through the properties in the XMLList: for each..in var total2:Number = 0;...
  • Page 328: Xml Type Conversion

    The XML class includes the following methods for working with namespaces: addNamespace() inScopeNamespaces() localName() name() namespace() , and namespaceDeclarations() removeNamespace() setLocalName() setName() setNamespace() directive lets you assign a default namespace for XML objects. default xml namespace For example, in the following, both have the same default namespace: var ns1:Namespace = new Namespace("http://www.example.com/ namespaces/");...
  • Page 329 If you use the method without specifying , the data trace() toString() toXMLString() is converted using the method by default, as this code shows: toString() var myXML:XML = <order> <item id='1' quantity='2'> <menuName>burger</menuName> <price>3.95</price> </item> <order>; trace(myXML.item[0].menuName); // burger When using the method to debug code, you will often want to use the trace() method so that the...
  • Page 330: Reading External Xml Documents

    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 function, the code would interpret the + operator as the Number() string concatenation operator, and the method in the last line would output the trace() following: 01.003.95 Reading external XML documents...
  • Page 331 The RSS format is widely used to syndicate news via XML. A simple RSS data file may look like the following: <?xml version="1.0" encoding="UTF-8" ?> <rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/"> <channel> <title>Alaska - Weather</title> <link>http://www.nws.noaa.gov/alerts/ak.html</link> <description>Alaska - Watches, Warnings and Advisories</description> <item> <title>...
  • Page 332 The RSSViewer application files can be found in the folder Samples/RSSViewer. The application consists of the following files: File Description RSSViewer.mxml The main application file in MXML for Flex. com/example/programmingas3/rssViewer/ A class that contains methods that use E4X to RSSParser.as traverse RSS (XML) data and generate a corresponding HTML representation.
  • Page 333 Assembling XMLList data The HTML data (an XMLList object) is of the following form: <b>itemTitle</b> <p> itemDescription <br /> <a href="link"> <font color="#008000">More...</font> </a> </p> The first lines of the method clear the default xml namespace: default xml namespace = new Namespace(); directive has function block-level scope.
  • Page 334 Extracting the title of the RSS feed and sending a custom event method sets a string variable, based on information in the source xmlLoaded() rssTitle RSS XML data: rssTitle = rssXML.channel.title.toString(); Finally, the method generates an event, which notifies the application that the xmlLoaded() data is parsed and available: dataWritten = new Event("dataWritten", true);...
  • Page 335 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 ..... 337 Chapter 13: Handling Events .
  • Page 337: Chapter 12: Flash Player Api Overview

    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 to Flash Player, as opposed to the top-level classes, such as Date, Math, and XML, or the language elements, which are based on ECMAScript.
  • Page 338: Flash.accessibility Package

    Contents flash.accessibility package ..........338 flash.display package .
  • Page 339: Flash.errors Package

    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 functionality and usage.
  • Page 340: Flash.external Package

    flash.external package The flash.external package contains only the ExternalInterface class, which was introduced in Flash Player 8 as a replacement for the function. ExternalInterface enables fscommand() communication between ActionScript and the Flash Player container—for example, an HTML page with JavaScript or a desktop application in which Flash Player is embedded. For more information, see “Using the External API”...
  • Page 341: Flash.media Package

    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 files and streaming sound embedded in a SWF file.
  • Page 342: Flash.profiler Package

    flash.profiler package This package contains the function, which can be useful for showRedrawRegions() debugging code. For more information, see the flash.profiler package in the ActionScript 3.0 Language Reference. flash.system package The flash.system package contains classes that provide system-level functionality and let you get limited, specified information about the functions of the client computer running Flash Player.
  • Page 343: Flash.utils Package

    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 functions that can control the time delay or intervals in which ActionScript code is executed.
  • Page 344 Flash Player API Overview...
  • Page 345 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. Based on the Document Object Model (DOM) Level 3 Events Specification, an industry- standard event handling architecture, the new event model provides a powerful yet intuitive event handling tool for ActionScript programmers.
  • Page 346: Chapter 13: 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 something more complex, such as accepting and processing data entered into a form.
  • Page 347: How Actionscript 3.0 Event Handling Differs From Earlier Versions

    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 is only one system for event handling, whereas in previous versions of ActionScript there are several different event handling systems.
  • Page 348 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 registering listener objects differs depending on whether you are using one of the six classes that support listeners or the UIEventDispatcher class.
  • Page 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 the cursor is highlighted. Many types of event objects do not have associated default behaviors.
  • Page 350: The Event Flow

    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 URLStream object. If the event target is on the display list, however, Flash Player dispatches the event object into the display list, and the event object travels through the display list to the event target.
  • Page 351 If a user clicks on , Flash Player dispatches an event object into the event flow. Child1 Node As the following image shows, the object’s journey starts at , moves down to Stage Parent , then moves to and then “bubbles” back up to , moving through Node Child1 Node,...
  • Page 352: Event Objects

    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 event handling system. First, event objects represent actual events by storing information about specific events in a set of properties.
  • Page 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 ACTIVATE:String = "activate";...
  • Page 354 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 property stores a Boolean value that Event.bubbles indicates whether the event object participates in the bubbling phase.
  • Page 355 For complex SWF files, especially those in which buttons are routinely decorated with smaller child objects, the property may not be used frequently because it will often point to a target button’s child object instead of the button. In these situations, the common practice is to add event listeners to the button and use the property because it points to the currentTarget...
  • Page 356 Stopping event flow You can call either the method or the Event.stopPropogation() method to prevent an event object from continuing Event.stopImmediatePropogation() on its way through the event flow. The two methods are nearly identical and differ only in whether the current node's other event listeners are allowed to execute: method prevents the event object from moving on to Event.stopPropogation() ■...
  • Page 357: Event Listeners

    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 defines several subclasses of the Event class.
  • Page 358 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 not have to be named —they can be named with any valid identifier.
  • Page 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 .
  • Page 360 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] Note that the keyword refers to the ChildSprite instance named .
  • Page 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); var myListenerObj:Object = new Object(); myListenerObj.clickHandler = function (event:MouseEvent):void trace("clickHandler detected an event of type: " + event.type); trace("the this keyword refers to: " + this); The results of the trace will look like this: clickHandler detected an event of type: click the this keyword refers to: [object global]...
  • Page 362 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):Boolean; function dispatchEvent(eventObject:Event):Boolean; function hasEventListener(eventName:String):Boolean; function willTrigger(eventName:String):Boolean; The Flash Player API implements the IEventDispatcher interface with the EventDispatcher class, which serves as a base class for all classes that can be event targets or part of an event flow.
  • Page 363 parameter of the method is not an official part of the priority addEventListener() 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 , you can addEventListener() set the priority for that event listener by passing an integer value as the parameter.
  • Page 364 Checking for existing event listeners The final two methods of the IEventDispatcher interface provide useful information about the existence of event listeners. The method returns if an event hasEventListener() true listener is found for a specific event type on a particular display list object. The method also returns if a listener is found for a particular display list willTrigger()
  • Page 365: Example: Alarm Clock

    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 with Dates and Times.”...
  • Page 366 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 determine when to trigger its alarm.
  • Page 367 The Timer instance defined in the AlarmClock class is named . The alarmTimer method, which performs necessary setup operations for the AlarmClock initClock() instance, does two things with the variable. First, the variable is instantiated with alarmTimer parameters instructing the Timer instance to wait 0 milliseconds and only trigger its timer event one time.
  • Page 368 This method does several things, including storing the alarm message and creating a Date object ( ) representing the actual moment in time when the alarm is to go off. Of alarmTime most relevance to the current discussion, in the final several lines of the method, the variable’s timer is set and activated.
  • Page 369 Other code can register to be notified of the AlarmClock class’s event by calling the alarm method that AlarmClock inherits from EventDispatcher. When an addEventListener() AlarmClock instance is ready to notify other code that its event has been raised, it does alarm so by calling the method, which is also inherited from EventDispatcher.
  • Page 370 @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 the preceding example. To supplement the inherited functionality, the AlarmEvent class defines a property that contains the text of the alarm message message...
  • Page 371 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, many of the classes within the flash.net package were top-level classes.
  • Page 372: Chapter 14: 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 earlier versions of ActionScript, you could load remote text files using the LoadVars class and the event handler.
  • Page 373: Working With External Data

    method (and optionally the URLLoader class’s constructor) takes a URLLoader.load() single parameter, , which is a URLRequest class object. A URLRequest object request contains all of the information for a single HTTP request, such as the target URL, request method ( ), additional header information, and the MIME type (for example, POST when you upload XML content).
  • Page 374 When you define variables within the URLVariables constructor or within the method, you need to make sure that you URL-encode the URLVariables.decode() ampersand ( ) character because it has a special meaning and acts as a delimiter. For example, & when you pass an ampersand, you need to URL-encode the ampersand by changing it from &...
  • Page 375 Once the data has loaded, the event is dispatched, and the contents of the Event.COMPLETE external document are available to use in the URLLoader’s property, as the following data code shows: private function completeHandler(event:Event):void var loader2:URLLoader = URLLoader(event.target); trace(loader2.data); If the remote document contains name-value pairs, you can parse the data using the URLVariables class by passing in the contents of the loaded file, as follows: private function completeHandler(event:Event):void var loader2:URLLoader = URLLoader(event.target);...
  • Page 376 The following code demonstrates how setting the property to URLLoader.dataFormat allows you to automatically parse loaded data into a URLLoaderDataFormat.VARIABLES URLVariables object: package import flash.display.Sprite; import flash.events.*; import flash.net.URLLoader; import flash.net.URLLoaderDataFormat; import flash.net.URLRequest; public class URLLoaderDataFormatExample extends Sprite public function URLLoaderDataFormatExample() var request:URLRequest = new URLRequest("http:// www.[yourdomain].com/params.txt");...
  • Page 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 is dispatched and the contents of the external file are converted to an Event.COMPLETE XML instance, which you can parse using XML methods and properties.
  • Page 378 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 send the user’s score to a server to calculate whether it should be added to the high scores list, or even send a user’s login information to a server for validation.
  • Page 379: Connecting To Other Flash Player Instances

    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 applications that can share data between Flash Player instances, such as SWF files running in a web browser or embedded in C# applications.
  • Page 380 There are three ways to add callback methods to your LocalConnection objects: Subclass the LocalConnection class and add methods. ■ Set the property to an object that implements the methods. LocalConnection.client ■ Create a dynamic class that extends LocalConnection and dynamically attach methods. ■...
  • Page 381 property indicates the object callback methods that should LocalConnection.client be invoked. In the previous code, the property was set to a new instance of a custom client class, CustomClient. The default value for the property is the current client LocalConnection instance. You can use the property if you have two data handlers client that have the same set of methods but act differently—for example, in an application where a...
  • Page 382 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 ServerLC() var lc:LocalConnection = new LocalConnection(); lc.client = new CustomClient1();...
  • Page 383 public function closeHandler(event:TimerEvent):void fscommand("quit"); To create a LocalConnection server, call the method and LocalConnection.connect() provide a unique connection name. If you already have a connection with the specified name, error is generated, indicating that the connection attempt failed because ArgumentError the object is already connected.
  • Page 384 Connecting to SWF documents in different domains To allow communications only from specific domains, you call the allowDomain() method of the LocalConnection class and pass a list of one or more allowInsecureDomain() domains that are allowed to access this LocalConnection object. In earlier versions of ActionScript, LocalConnection.allowDomain() were callback methods that had to be...
  • Page 385: Socket Connections

    If you implement communication between SWF files in different domains, you specify a parameter that begins with an underscore ( ). Specifying the underscore connectionName makes the SWF file with the receiving LocalConnection object more portable between domains. Here are the two possible cases: If the string for does not begin with an underscore ( ), Flash Player adds...
  • Page 386 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 class is useful for interoperating with servers that use binary protocols.
  • Page 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 XMLSocket class, the server computer must run a daemon that understands the protocol used by the XMLSocket class.
  • Page 388 When you invoke the method, Flash Player opens a TCP/IP XMLSocket.connect() connection to the server and keeps that connection open until one of the following occurs: method of the XMLSocket class is called. ■ XMLSocket.close() No more references to the XMLSocket object exist. ■...
  • Page 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"); boolean done = false; while (!done) String str = readerIn.readLine(); if (str == null) done = true; else out("Echo: "...
  • Page 390: Storing Local Data

    To connect to the XMLSocket from your ActionScript application, you need to create a new instance of the XMLSocket class, and call the method while passing a XMLSocket.connect() host name and port number, as follows: var xmlsock:XMLSocket = new XMLSocket(); xmlsock.connect("127.0.0.1", 8080);...
  • Page 391: Storing Local Data

    New shared object instances can be created using the static SharedObject.getLocal() methods. The method attempts to load a locally SharedObject.getRemote() getLocal() persistent shared object that is available only to the current client, whereas the getRemote() method attempts to load a remote shared object that can be shared across multiple clients by means of a server, such as Flash Media Server.
  • Page 392 Flash Player Settings Manager (http://www.macromedia.com/support/documentation/en/flashplayer/ help/settings_manager07.html), as shown in the following example: var so:SharedObject = SharedObject.getLocal("test"); trace("Current SharedObject size is " + so.size + " bytes.");...
  • Page 393 trace(i + ":\t" + so.data[i]); Creating a secure SharedObject When you create either a local or remote SharedObject using getLocal() getRemote() there is an optional parameter named that determines whether access to this shared secure object is restricted to SWF files that are delivered over an HTTPS connection. If this parameter is set to and your SWF file is delivered over HTTPS, Flash Player creates a true...
  • Page 394: Working With File Upload And Download

    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 on the Windows operating system).
  • Page 395: Working With File Upload And Download

    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 refers to a single file on the user’s disk and has properties that contain information about the file’s size, type, name, creation date, modification date, and creator.
  • Page 396 ------------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 ------------Ij5ae0ae0KM7GI3KM7ei4cH2ei4gL6 Content-Disposition: form-data; name="Upload" Submit Query ------------Ij5ae0ae0KM7GI3KM7ei4cH2ei4gL6 (actual file data,,,) The following sample HTTP request sends three variables: , and POST POST api_sig api_key , and uses a custom upload data field name value of auth_token "photo"...
  • Page 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 method to allow a user to select one or more browse() files. Next, when the method is called, the selected file will be FileReference.upload() transferred to the server.
  • Page 398 var request:URLRequest = new URLRequest("http://www.[yourdomain].com/ fileUploadScript.cfm") fileRef.upload(request); catch (error:Error) trace("Unable to upload file."); function completeHandler(event:Event):void trace("uploaded"); You can send data to the server with the method by using the FileReference.upload() properties to send variables using the URLRequest.method URLRequest.data POST methods. When you attempt to upload a file using the method, any of the FileReference.upload()
  • Page 399 parameter contains an invalid protocol. The FileReference.upload() ■ method must use either HTTP or HTTPS. Flash Player does not offer complete support for servers that require authentication. Only SWF files that are running in a browser using the browser plug-in or ActiveX control can provide a dialog box to prompt the user to enter a user name and password for authentication, and then only for downloads.
  • Page 400 $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) - $MAXIMUM_FILE_COUNT); for ($i = 0; $i < count($files_to_delete); $i++) unlink($files_to_delete[$i][0]); print_r($files); closedir($directory); function sorter($a, $b) if ($a[1] == $b[1]) return 0;...
  • Page 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 script by passing values in the query string. ActionScript 3.0 allows you to pass variables to the remote script using a URLRequest object, which allows you to pass data using either the POST method;...
  • Page 402 To set the default name to currentnews.xml instead of index.xml, specify the parameter, as the following snippet shows: defaultFileName var request:URLRequest = new URLRequest("index.xml"); var fileToDownload:FileReference = new FileReference(); fileToDownload.download(request, "currentnews.xml"); Renaming a file can be very useful if the server filename was not intuitive or was server- generated.
  • Page 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: <cfparam name="URL.id" default="1" /> <cfswitch expression="#URL.id#"> <cfcase value="2"> <cfcontent type="text/plain" file="#ExpandPath('two.txt')#" deletefile="No" /> </cfcase> <cfdefaultcase> <cfcontent type="text/plain"...
  • Page 404: Example: Building A Telnet Client

    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 < selectedFileArray.length; i++) file = FileReference(selectedFileArray[i]); file.addEventListener(Event.COMPLETE, completeHandler); file.upload(request); catch (error:Error) trace("Unable to upload files."); function completeHandler(event:Event):void trace("uploaded"); Because the event is added to each individual FileReference object in the Event.COMPLETE...
  • Page 405 The Telnet application files can be found in the Samples/Telnet folder. The application consists of the following files: File Description TelnetSocket.mxml The main application file consisting of the MXML user interface. com/example/programmingas3/Telnet/ Provides the Telnet client functionality for the Telnet.as application, such as connecting to a remote server, and sending, receiving, and displaying data.
  • Page 406 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, , that will be initialized later by the method. Next, telnetClient connect() method is declared and initializes the variable declared earlier.
  • Page 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.addEventListener(ErrorEvent.ERROR, errorHandler); socket.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler); socket.addEventListener(ProgressEvent.SOCKET_DATA, dataHandler); Security.loadPolicyFile("http://" + serverURL + "/crossdomain.xml"); msg("Trying to connect to " + serverURL + ":" + portNumber + "\n"); socket.connect(serverURL, portNumber);...
  • Page 408: Example: Uploading And Downloading Files

    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 method, which causes the TextArea component to scroll to the very setScroll() bottom.
  • Page 409: Example: Uploading And Downloading Files

    The FileIO application files are found in the Samples/FileIO folder. The application consists of the following files: File Description FileIO.mxml The main application file consisting of the MXML user interface. com/example/programmingas3/fileio/ A class that includes methods for downloading FileDownload.as files from a server. com/example/programmingas3/fileio/ A class that includes methods for uploading FileUpload.as...
  • Page 410 This code places a ProgressBar component instance and two Button component button instances on the Stage. When the user clicks the Upload button ( , an operating startUpload) system dialog box is launched that allows the user to select a file to upload to a remote server. The other button, , is disabled by default, although when a user begins a file cancelUpload...
  • Page 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, , contains the path to the file, which gets downloaded onto DOWNLOAD_URL the user’s computer when the user clicks the Download button in the main application file.
  • Page 412 Beginning the file download When the user clicks the Download Button component instance on the Stage, the method is to initiate the file download process. The following excerpt startDownload() shows the method: startDownload() * Begin downloading the file specified in the DOWNLOAD_URL constant. public function startDownload():void var request:URLRequest = new URLRequest();...
  • Page 413 Monitoring a file’s download progress As a file downloads from a remote server to the user’s computer, the event progress ) is dispatched at regular intervals. Whenever the event ProgressEvent.PROGRESS progress is dispatched, the method is invoked and the ProgressBar component progressHandler() instance on the Stage is updated.
  • Page 414 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 cancelled. Finally, the Cancel button is disabled, which prevents the user from clicking the button again until they attempt to download the file again.
  • Page 415 Beginning a file upload The file upload is initiated when the user clicks on the Upload button on the Stage, which invokes the method. This method calls the method FileUpload.startUpload() browse() of the FileReference class which causes the operating system to display a system dialog box prompting the user to select a file to upload to the remote server.
  • Page 416 Networking and Communication...
  • Page 417: Using Point Objects

    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 ............417 Using Rectangle objects .
  • Page 418: Chapter 15: Working With Geometry

    Finding the distance between two points You can use the method of the Point class to find the distance between two distance() points in a coordinate space. For example, the following code finds the distance between the registration points of two display objects, , in the same display object circle1 circle2...
  • Page 419: Using Point Objects

    Moving a display object by a specified angle and distance You can use the method of the Point class to move a display object a specific distance polar() by a specific angle. For example, the following code moves the object 100 myDisplayObject pixels by 60 degrees: import flash.geom.*;...
  • Page 420: Using Rectangle Objects

    Using Rectangle objects A Rectangle object defines a rectangular area. A Rectangle object has a position, defined by coordinates of its top-left corner, a property, and a property. You width height can define these properties for a new Rectangle object by invoking the Rectangle() constructor function, as follows: import flash.geom.Rectangle;...
  • Page 421 Similarly, as the following example shows, if you change the property of a bottom right 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:Number = 100;...
  • Page 422 Finding unions and intersections of Rectangle objects You use the method to find the rectangular region formed by the boundaries of two union() rectangles: import flash.display.*; import flash.geom.Rectangle; var rect1:Rectangle = new Rectangle(0, 0, 100, 100); trace(rect1); // (x=0, y=0, w=100, h=100) var rect2:Rectangle = new Rectangle(120, 60, 100, 100);...
  • Page 423: Using Matrix Objects

    Other uses of Rectangle objects Rectangle objects are used in the following methods and properties: Class Methods or properties Description BitmapData Used as the type for applyFilter(), colorTransform(), some parameters to copyChannel(), copyPixels(), define a region of the draw(), fillRect(), BitmapData object.
  • Page 424 Defining Matrix objects Although you could define a matrix by directly adjusting the properties ( ) of a Matrix object, it is easier to use the method. This method includes parameters createBox() that let you directly define the scaling, rotation, and translation effects of the resulting matrix. For example, the following code creates a Matrix object that has the effect of scaling an object horizontally by 2.0, scaling it vertically by 3.0, rotating it by 45 degrees, moving (translating) it 10 pixels to the right, and moving it 20 pixels down:...
  • Page 425 matrix.rotate(rotation); myDisplayObject.transform.matrix = matrix; The first line sets a Matrix object to the existing transformation matrix used by the display object (the property of the property of myDisplayObject matrix transformation display object). This way, the Matrix class methods that you call will myDisplayObject have a cumulative effect on the display object’s existing position, scale, and rotation.
  • Page 426 The following examples show gradients in which the parameter of the rotation method differs as indicated, but all other settings stay the same: createGradientBox() width = 100; height = 100; rotation = 0; tx = 0; ty = 0; width = 100; height = 100;...
  • Page 427 The following examples show the effects on a green-to-blue linear gradient in which the , and parameters of the method differ as indicated, rotation createGradientBox() but all other settings stay the same: width = 50; height = 100; rotation = 0; tx = 0;...
  • Page 428: Example: Applying A Matrix Transformation To A Display Object

    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:Array = [0, 255]; var spreadMethod:String = SpreadMethod.PAD; var interp:String = InterpolationMethod.LINEAR_RGB; var focalPtRatio:Number = 0;...
  • Page 429: Example: Applying A Matrix Transformation To A Display Object

    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 object, and the display object rotated by -45 and scaled by 50% °...
  • Page 430 The DisplayObjectTransformer application files can be found in the folder Samples/ DisplayObjectTransformer. The application consists of the following files: File Description DisplayObjectTransformer.mxml The main application file in MXML for Flex. com/example/programmingas3/geometry/ A class that contains methods for applying MatrixTransformer.as matrix transformations. img/ A directory containing sample image files used by the application.
  • Page 431 The skew() method method skews the matrix by adjusting the properties of the matrix. An skew() optional parameter, , determines the units used to define the skew angle, and if necessary, unit the method converts the value to radians: angle if (unit == "degrees") angle = Math.PI * 2 * angle / 360;...
  • Page 432 The translate() method method simply applies the translation factors by calling the translate() method of the matrix object, as follows: translate() sourceMatrix.translate(dx, dy); return sourceMatrix; The rotate() method method converts the input rotation factor to radians (if it is provided in rotate() degrees or gradients), and then calls the method of the matrix object:...
  • Page 433: Chapter 16: Client System Environment

    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 user’s Flash Player, building multilingual sites using the Input Method Editor (IME), interacting with the Flash Player’s container (which could be an HTML page or a container application), or saving information to the user’s Clipboard.
  • Page 434: Chapter 16: Client System Environment

    Getting data about the user’s system at runtime By checking the property, you can determine the amount of memory System.totalMemory (in bytes) that Flash Player is currently using. This property allows you to monitor memory usage and optimize your applications based on how the memory level changes. For example, if a particular visual effect causes a large increase in memory usage, you may want to consider modifying the effect or eliminating it altogether.
  • Page 435: Capabilities Class

    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 software, and the language of the user’s operating system, as well as the version of the currently installed Flash Player.
  • Page 436: Applicationdomain Class

    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 domain. This allows multiple definitions of the same class to exist and also lets children reuse parent definitions.
  • Page 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 domains, including the current domain, which means that it contains all Flash Player classes.
  • Page 438 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 application domain for each SWF file in an application.
  • Page 439: Ime Class

    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 Flash Player. Using ActionScript, you can determine the following: If an IME is installed on the user's computer ( Capabilities.hasIME ■...
  • Page 440 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 installed and active before you call any methods: if (Capabilities.hasIME) if (IME.enabled) trace("IME is installed and enabled.");...
  • Page 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 Japanese Katakana (half- width)."; break; case IMEConversionMode.KOREAN: tf.text = "Current conversion mode is Korean."; break;...
  • Page 442 statusText.text = "Unable to set conversion mode.\n" + 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 if (Capabilities.hasIME) IME.enabled = true; This example creates two input text fields, , and then adds two event phoneTxt nameTxt listeners to the text field. When the user sets focus to the text field, a phoneTxt phoneTxt event is dispatched and the IME is disabled. When the text FocusEvent.FOCUS_IN phoneTxt...
  • Page 444: Example: Detecting System Capabilities

    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: " + event.text; The previous code creates two text fields and adds them to the display list. The first text field, , is an input text field that allows the user to enter Japanese text.
  • Page 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 Stage. Their browser capabilities will also be displayed if they are running the application from an HTML container and if the External API is available.
  • Page 446 capDP.sortOn("name", Array.CASEINSENSITIVE); return capDP; method returns an array of each of the propreties in the browser’s getBrowserObjects() navigator object. If this array has a length of one or more items, the array of browser capabilities ( ) is appended to the arrray of Flash Player capabilities ( ), and the navArr capDP...
  • Page 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 for the JavaScript JS_getBrowserObjects() method in the container.html file is as follows: <script language="JavaScript">...
  • Page 448 return tempArr.join("&"); </script> 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 loop, and the data for..in type of the current value is evaluated to filter out unwanted values. In this application, we are interested only in String or Boolean values, and other data types (such as functions or arrays) are ignored.
  • Page 449 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 work with the Flash Player security model when you are developing Flash applications.
  • Page 450: Chapter 17: 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 put in the same security grouping, known as a security sandbox.
  • Page 451: Flash Player Security Overview

    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 media. Data is defined as something that is accessible only to ActionScript code.
  • Page 452: Overview Of Permission Controls

    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 controls (security settings) over their own resources, and each resource has four stakeholders.
  • Page 453: Overview Of Permission Controls

    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\macromed\flash\mms.cfg on a default Windows XP installation).
  • Page 454 Mac: app support/Macromedia/FlashPlayerTrust ■ (for example, /Library/Application Support/Macromedia/FlashPlayerTrust) The Flash Player Trust directory can contain any number of text files, each of which lists trusted paths, with one path per line. Each path can be an individual SWF file, HTML file, or directory.
  • Page 455 User Flash Player Trust directory, which is in same directory as the Flash shared object storage area, in the following locations (locations are specific to the current user): Windows: app data\Macromedia\Flash Player\#Security\FlashPlayerTrust ■ (for example, C:\Documents and Settings\JohnD\Application Data\Macromedia\Flash Player\#Security\FlashPlayerTrust) Mac: app data/Macromedia/Flash Player/#Security/FlashPlayerTrust ■...
  • Page 456 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 trusted for that user.
  • Page 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 accessible. By default, policy files must be named and must reside in the root crossdomain.xml...
  • Page 458 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 you must keep the loading SWF file on an HTTP server, add the secure="false"...
  • Page 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 same host as the socket server.
  • Page 460 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 www.example.com domain: Security.allowDomain("www.example.com") This method grants permissions for the following: Cross-scripting between SWF files (see...
  • Page 461: Security Sandboxes

    Another important security-related method is the method, Security.loadPolicyFile() 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 sandboxes Client computers can obtain individual SWF files from a number of sources, such as from external websites or from a local file system.
  • Page 462 Local sandboxes Local file describes any file that is referenced by using the protocol or a Universal file: 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 places all local ■...
  • Page 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 a SWF file for the local-with-filesystem sandbox or the local-with- networking sandbox by setting the use-network flag in the Flex compiler.
  • Page 464: Restricting Networking Apis

    <param name="bgcolor" value="#333333" /> <embed src="test.swf" allowNetworking="none" bgcolor="#333333" width="600" height="400" name="test" align="middle" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" /> </object> An HTML page may also use a script to generate SWF-embedding tags. You need to alter the script so that it inserts the proper settings.
  • Page 465: Full-Screen Mode Security

    An addition to those APIs on the previous list, the following APIs are also prevented when is set to allowNetworking "none" sendToURL() ■ ■ FileReference.download() ■ FileReference.upload() Loader.load() ■ ■ LocalConnection.connect() ■ LocalConnection.send() NetConnection.connect() ■ ■ NetStream.play() ■ Security.loadPolicyFile() SharedObject.getLocal() ■...
  • Page 466 <param name="bgcolor" value="#333333" /> <embed src="test.swf" allowFullScreen="true" bgcolor="#333333" width="600" height="400" name="test" align="middle" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" /> </object> An HTML page may also use a script to generate SWF-embedding tags. You must alter the script so that it inserts the proper settings. HTML pages generated by...
  • Page 467: Loading Content

    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, can load SWF files and images from any network domain.
  • Page 468 When you call the method of the Loader object, you can specify a load() 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: —Use this property only when loading an image file (not a SWF file).
  • Page 469 An important property of a Loader object is the property, which is a contentLoaderInfo 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 content is a SWF file, it can access the LoaderInfo object through the property.
  • Page 470: Cross-Scripting

    When you use an tag in a text field to load an external file (as opposed to using a <img> 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 a Loader object in ActionScript to load the file.
  • Page 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 permission to SWF files from other domains by calling .
  • Page 472 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 method. When HTML-to-SWF scripting crosses ExternalInterface.addCallback() domains, the SWF file being accessed must call the method, just...
  • Page 473 There are also restrictions on the methods of the removeChildAt() swapChildrenAt() 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 owner of the affected child object(s), or the child object(s) can call the method.
  • Page 474: Accessing Loaded Media As Data

    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() . By default, a SWF file from one security sandbox cannot SoundMixer.computeSpectrum() obtain pixel data or audio data from graphic or audio objects rendered or played by loaded media in another sandbox.
  • Page 475 When you load the image using the method of the Loader class, you can specify a load() parameter, which is a LoaderContext object. If you set the context checkPolicyFile property of the LoaderContext object to , Flash Player checks for a cross-domain policy true file on the server from which the image is loaded.
  • Page 476 You can use the method to find out whether a call SoundMixer.areSoundsInaccessible() to the method would not stop all sounds because the sandbox of one SoundMixer.stopAll() or more sound owners is inaccessible to the caller. Calling the method stops those sounds whose owner sandbox is the SoundMixer.stopAll() same as that of the caller of .
  • Page 477: Loading Data

    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. Generally, SWF files may load data from their own domains.
  • Page 478 To retrieve a socket policy file from the same port as a main socket connection, simply call the method, and, if the specified domain is not Socket.connect() XMLSocket.connect() the same as the domain of the calling SWF file, Flash Player automatically attempts to retrieve a policy file from the same port as the main connection you are attempting.
  • Page 479: Loading Embedded Content From Swf Files Imported Into A Security Domain

    Uploading and downloading files method starts the upload of a file selected by a user to a FileReference.upload() remote server. You must call the FileReference.browse() method before calling the FileReferenceList.browse() FileReference.upload() method. Calling the method opens a dialog box in which the user can FileReference.download() download a file from a remote server.
  • Page 480: Working With Legacy Content

    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 method to grant Security.allowDomain() access to the domain of the calling SWF file. You can add the call to the method to the constructor method of the main class of the loaded Security.allowDomain() SWF file, and then have the loading SWF file add an event listener to respond to the...
  • Page 481: Setting Localconnection Permissions

    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 can be running in different applications—for example, a SWF file running in a browser and a SWF file running in a projector.
  • Page 482 Set this parameter in the HTML code for the web page that hosts a SWF file. You set the parameter in the tag. PARAM EMBED parameter can have one of three possible values: AllowScriptAccess "always" , or "sameDomain" "never" When , outbound scripting is allowed only if the ■...
  • Page 483: Shared Objects

    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 security sandboxes.
  • Page 484: Camera, Microphone, Clipboard, Mouse, And Keyboard Access

    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 property set to .
  • Page 485 method allows a SWF file to replace the contents of the System.setClipboard() 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 cut or copied to Clipboards, there is no corresponding “getClipboard”...
  • Page 486 Flash Player Security...
  • Page 487: Chapter 18: Printing

    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 and dynamic text.
  • Page 488: What's New For The Printjob Class Using Actionscript 3.0

    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: method now takes a Sprite and a Rectangle object for the first PrintJob.addPage() ■...
  • Page 489: Flash Player Tasks And System Printing

    So, for example, a very simple print job script may look like the following (including statements for compiling): package import class package import flash.printing.PrintJob; import flash.display.Sprite; public class BasicPrintExample extends Sprite var myPrintJob:PrintJob = new PrintJob(); var mySprite:Sprite = new Sprite(); public function BasicPrintExample() myPrintJob.start();...
  • Page 490 Working with exceptions and returns You should check to see if the method returns before executing PrintJob.start() true calls, in case the user has cancelled the print job. A simple way to addPage() send() check whether these methods have been cancelled before continuing is to wrap them in an statement, as follows: if (myPrintJob.start()) // addPage() and send() statements here...
  • Page 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 or providing an alert within the Flash animation).
  • Page 492 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.
  • Page 493: Setting Size, Scale, And Orientation

    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 different resolutions for printing, and can have settings that adversely affect the appearance of the printed sprite.
  • Page 494 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 between pixels and points depends on the printer settings and whether the sprite is scaled.
  • Page 495: Example: Multiple-Page Printing

    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: if (myPrintJob.orientation == PrintJobOrientation.LANDSCAPE) mySprite.rotation = 90;...
  • Page 496 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 a time...", {x:10, y:50, width:80, height:130}); sheet2 = new Sprite(); createSheet(sheet2, "There was a great story to tell, and it ended quickly.\n\nThe end.", null);...
  • Page 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; sheet2.height = pj.pageHeight; sheet2.width = pj.pageWidth; pj.addPage(sheet1); pagesToPrint++; catch (e:Error) // Respond to error.
  • Page 498: Example: Scaling, Cropping, And Responding

    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 display object before printing (for example, by using the properties), be aware that if the object scales scaleX...
  • Page 499 trace(">> pj.paperHeight: " + pj.paperHeight); 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.scaleY = 1; private function init():void bg = new Sprite(); bg.graphics.beginFill(0x00FF00);...
  • Page 500 Printing...
  • Page 501 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, when you create interaction between a SWF document and JavaScript in an HTML page, or when building a desktop application that uses Flash Player to display a SWF file.
  • Page 502: Chapter 19: 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 projector application).
  • Page 503: Using The Externalinterface Class

    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 ■ function.
  • Page 504 Getting information about the external container property indicates whether the current Flash Player is ExternalInterface.available in a container that offers an external interface. If the external interface is available, this property is ; otherwise, it is . Before using any of the other functionality in the true false ExternalInterface class, you should always check to make sure that the current container...
  • Page 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 <script> page. The return value of the JavaScript function is passed back to ActionScript. <script language="JavaScript">...
  • Page 506 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 function with the ExternalInterface class, and then call it from the container’s code.
  • Page 507: Example: Using The External Api With A Web Page Container

    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 ActiveX container. Example: Using the External API with a web page container This example application demonstrates appropriate techniques for communicating between...
  • Page 508 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. Because of the complexity of browsers and how they render pages internally, there is no way to guarantee that a SWF document will register its callbacks before the first JavaScript on the HTML page runs.
  • Page 509 First of all, the code checks whether the External API is even available in the current container using the property. If so, it begins the process of setting up ExternalInterface.available communication. Because security exceptions and other errors can occur when you attempt communication with an external application, the code is wrapped in a block (the corresponding...
  • Page 510 Back in the IMManager constructor, one of two things happens depending on the readiness of the container. If returns , the code simply calls the isContainerReady() true method, which completes the process of setting up communication with setupCallbacks() JavaScript. On the other hand, if returns , the process is isContainerReady()
  • Page 511 method finishes the task of preparing for communication with the setCallBacks() container by calling to register the two methods that ExternalInterface.addCallback() will be available to be called from JavaScript. In this code, the first parameter—the name by which the method is known to JavaScript ( )—is the same as "newMessage"...
  • Page 512 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 to and ask for information from the SWF file as well.
  • Page 513 ActionScript method returns a value, and that value is assigned to the ■ getStatus() variable, which is then assigned as the content (the property) of currentStatus value text field. status If you’re following along in the code, you’ve probably noticed that in the source code for function, the line of code that calls the function, is actually updateStatus()
  • Page 514: Example: Using The External Api With An Activex Container

    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 shown in the JavaScript getSWF() function in this example:...
  • Page 515: Example: Using The External Api With An Activex Container

    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/IntrovertIMApp.swf The SWF file loaded by the application. ExternalInterfaceProxy/ The class that serves as a wrapper around the ExternalInterfaceProxy.cs...
  • Page 516 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® Flash ActiveX control, within which the SWF file containing the ActionScript IM client is loaded.
  • Page 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, when ActionScript communicates with a web browser, as far as the developer is concerned, the functions are called directly;...
  • Page 518 The application declares and creates an ExternalInterfaceProxy instance named , passing proxy in a reference to the Shockwave Flash ActiveX control that is in the user interface ). Next, the code registers the method IntrovertIMApp proxy_ExternalInterfaceCall() to receive the proxy’s event.
  • Page 519 An ExternalInterfaceCall instance is a simple value object with two properties. The property contains the function name specified in the ActionScript FunctionName statement. If any parameters are added in ActionScript, those ExternalInterface.Call() parameters are included in the ExternalInterfaceCall object’s property. In this case, Arguments the method that handles the event is simply a statement that acts like a traffic...
  • Page 520 As this example shows, the ExternalInterfaceProxy class’s method is very similar to its Call() ActionScript counterpart, . The first parameter is a string, the ExternalInterface.Call() name of the function to call. Any additional parameters (not shown here) are passed along to the ActionScript function.
  • Page 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 intends to receive calls from a SWF file needs to define a handler for that event.
  • Page 522 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 possible for the code in the application form to ignore this format and operate directly on the values.
  • Page 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 C# class/ Format Comments class/value value null null <null/> Boolean bool true <true/> true Boolean bool false <false/>...
  • Page 524 Using the External API...

This manual is also suitable for:

Flex

Table of Contents