Flex2 Migrationguide
Flex2 Migrationguide
Adobe Flex 2
Migrating Applications to Flex 2
© 2006 Adobe Systems Incorporated. All rights reserved.
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. Please note
that the content in this guide is protected under copyright law even if it is not distributed with software that includes an end-user
license agreement.
The content of this guide is furnished for informational use only, is subject to change without notice, and should not be
construed as a commitment by Adobe Systems Incorporated. Adobe Systems Incorporated assumes no responsibility or liability
for any errors or inaccuracies that may appear in the informational content contained in this guide.
Please remember that existing artwork or images that you may want to include in your project may be protected under copyright
law. The unauthorized incorporation of such material into your new work could be a violation of the rights of the copyright
owner. Please be sure to obtain any permission required from the copyright owner.
Any references to company names in sample templates are for demonstration purposes only and are not intended to refer to any
actual organization.
Adobe, the Adobe logo, Flex, Flex Builder and Flash Player are either registered trademarks or trademarks of Adobe Systems
Incorporated in the United States and/or other countries. All other trademarks are the property of their respective owners.
Adobe Systems Incorporated, 345 Park Avenue, San Jose, California 95110, USA
Notice to U.S. government end users. The software and documentation are “Commercial Items,” as that term is defined at 48
C.F.R. §2.101, consisting of “Commercial Computer Software” and “Commercial Computer Software Documentation,” as such
terms are used in 48 C.F.R. §12.212 or 48 C.F.R. §227.7202, as applicable. Consistent with 48 C.F.R. §12.212 or 48 C.F.R.
§§227.7202-1 through 227.7202-4, as applicable, the Commercial Computer Software and Commercial Computer Software
Documentation are being licensed to U.S. Government end users (a) only as Commercial items and (b) with only those rights as
are granted to all other end users pursuant to the terms and conditions herein. Unpublished-rights reserved under the copyright
laws of the United States. Adobe Systems Incorporated, 345 Park Avenue, San Jose, CA 95110-2704, USA. For U.S.
Government End Users, Adobe agrees to comply with all applicable equal opportunity laws including, if appropriate, the
provisions of Executive Order 11246, as amended, Section 402 of the Vietnam Era Veterans Readjustment Assistance Act of
1974 (38 USC 4212), and Section 503 of the Rehabilitation Act of 1973, as amended, and the regulations at 41 CFR Parts 60-1
through 60-60, 60-250 ,and 60-741. The affirmative action clause and regulations contained in the preceding sentence shall be
incorporated by reference.
Contents
3
Events . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84
Formatters. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89
Interfaces. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 90
Managers. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91
Media controls . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 94
Printing. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 94
Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95
Service tags . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95
Skins. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97
States . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 98
Utilities . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99
Validators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99
4 Contents
Chapter 9: Data Services. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 135
About Data Services . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .135
Migrating RemoteObject components . . . . . . . . . . . . . . . . . . . . . . . . . . 137
Migrating HTTPService components . . . . . . . . . . . . . . . . . . . . . . . . . . .140
Migrating WebService components . . . . . . . . . . . . . . . . . . . . . . . . . . . .143
Migrating secure data services . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .145
Mapping Java types for RemoteObject. . . . . . . . . . . . . . . . . . . . . . . . . .150
Accessing request/response data with RemoteObject . . . . . . . . . . . .152
Contents 5
6 Contents
About Flex Documentation
Contents
Using this manual . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
Accessing the Flex documentation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
7
Documentation set
The Flex documentation set includes the following titles:
Book Description
Flex 2 Developer’s Guide Describes how to develop your dynamic web
applications.
Getting Started with Flex 2 Contains an overview of Flex features and
application development procedures.
Creating and Extending Flex 2 Describes how to create and extend Flex
Components components.
Typographical conventions
The following typographical conventions are used in this book:
■ Italic font indicates a value that should be replaced (for example, in a folder path).
■ Code font indicates code.
■ Code font italic indicates a parameter.
■ Boldface font indicates a verbatim entry.
Getting Started 1
This topic describes the first steps of migrating a Macromedia Flex 1.x application to Adobe
Flex 2. This topic describes steps that are meant to be accomplished quickly and resolve most
of the warnings and errors that you encounter. When you complete the steps in this topic, you
should read other topics in this manual for more information about specific migration
operations.
Contents
Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
Step 1: Find and replace . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
Step 2: Add access modifiers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
Step 3: Add types. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
Step 4: Update events. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
Step 5: Import classes for package-level functions . . . . . . . . . . . . . . . . . . . . . . . . . . . .17
Step 6: Put all ActionScript components in packages. . . . . . . . . . . . . . . . . . . . . . . . . .17
Step 7: Update data services . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
Step 8: Charts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
Step 9: Overrides . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
Step 10: Binding . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
Step 11: API updates . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
Introduction
You should undertake the migration process in a series of steps. The earlier steps involve
simple tasks, such as finding and replacing, or adding access modifiers. This topic describes
these steps. The later steps are more involved and require you to read other topics in this
manual. For example, when you convert portions of an application that uses binding, you
should read Chapter 5, “Binding,” on page 105.
9
The basic steps are the following:
■ “Step 1: Find and replace” on page 10
■ “Step 2: Add access modifiers” on page 14
■ “Step 3: Add types” on page 15
■ “Step 4: Update events” on page 16
■ “Step 6: Put all ActionScript components in packages” on page 17
■ “Step 7: Update data services” on page 18
■ “Step 8: Charts” on page 18
■ “Step 9: Overrides” on page 18
■ “Step 10: Binding” on page 19
■ “Step 11: API updates” on page 19
The remaining sections of this topic describe these steps in detail.
10 Getting Started
This section describes only the most common targets of finding and replacing. There are
many other members of Flex classes that have changed that are not mentioned here. For a
complete list, see Chapter 3, “Flex Classes,” on page 41.
Application namespace
Change the MXML namespace. Change the following:
xmlns:mx="http://www.macromedia.com/2003/mxml"
to this:
xmlns:mx="http://www.adobe.com/2006/mxml"
For example:
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
Void
Replace Void (with a capital V) with void (with a lower-case v).
Newline
The newline constant has been removed. In ActionScript, use “\n” to add a carriage return in
your Strings. In an MXML tag, use the XML character entity to add a carriage return.
In calls to the setStyle() method, you can prefix RRGGBB color values with 0x or #, but
you must put quotation marks around constants and # values; for example:
b1.setStyle("color",0xFF0000); // Valid
b2.setStyle("color","red"); // Valid
b3.setStyle("color","#FF0000"); // Valid
b4.setStyle("color",red); // Invalid
b5.setStyle("color",#FF0000); // Invalid
For more information on changes to the supported color value formats, see “Using colors”
on page 121.
Event.currentTarget
Use the currentTarget property rather than the target property of the Event object. The
Event object now has two properties: target and currentTarget. The former is the object
that originally dispatched the event, and the latter is the object to which your event handler is
attached. The two are often the same, but they may differ if the event has bubbled up from a
child object.
In most cases, you will want to change the target property to the currentTarget property,
because the object that was previously the target is now most likely the current target; for
example:
switch (event.currentTarget.className) { ... }
For more information, see “Using the target property” on page 113.
Uninitialized values
Remove checks against the undefined value. In Flex 2, undefined is only for use with the *
(no-type) “type”. Other types can no longer store the undefined value. If you assign
undefined to other types, it will be coerced into null, NaN, 0, or false. You can use the
isNaN() method to check if a variable is NaN.
If you do not initialize a variable at all, the initial value is different than in Flex 1.x. For more
information, see “Initializing variables” on page 29.
12 Getting Started
Replace _root
Remove the use of “_root” from your application code if you used it to access the Application
instance. In Flex 1.x, you could use _root to refer to the main application from anywhere in
your application or one of the components. This was never a recommended practice, but was
a convenient way to access the application root. To access the Application instance from
anywhere in your application, use Application.application.
import mx.core.Application;
function myFunction():void {
//_root.ta1.text = "Thank you!"; // Flex 1.x
Application.application.ta1.text = "Thank you!"; // Flex 2
}
Alerts
The Application.alert() convenience method was removed. You must now use the
mx.controls.Alert.show() method. You import the mx.controls.Alert class and call the
Alert.show() method, as the following example shows:
import mx.controls.Alert;
public function myEventHandler(event:Event):void {
Alert.show("An event occurred!");
}
If you call the show() method in an MXML tag, then you must also include a script block
that imports the mx.controls.Alert class, as the following example shows:
<?xml version="1.0"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:Script><![CDATA[
import mx.controls.Alert;
]]></mx:Script>
<mx:Button id="b1" label="Show Style" click="Alert.show('Alert!');"/>
</mx:Application>
getURL() method
Replace the getURL() method with the navigateToURL() method in the flash.net package.
This global method takes a URLRequest object; for example:
var url:URLRequest = new URLRequest("http://mysite.com");
navigateToURL(url,"_self");
For more information, see Chapter 34, “Communicating with the Wrapper,” in Flex 2
Developer’s Guide.
var s = "My name is Fred."; private var s:String = "My name is Fred.";
class MyButton extends Button { ... } public class MyButton extends Button { ... }
14 Getting Started
The default access modifier for methods, variables, and classes is internal. This means that
all classes in the same package can access them, but classes outside of the package cannot.
However, the Flex compiler issues a warning if you do not specify any access modifier.
For more information about access modifiers, see “Access modifiers” on page 27. For
information about disabling warnings, see Chapter 9, “Using the Flex Compilers,” in Building
and Deploying Flex 2 Applications.
To find methods and method arguments, search for the keyword function and add a return
type if that method returns a value and type each method argument; for example:
Flex 1.x:
function getAnswer(myString) {
...
return myString;
}
Flex 2:
public function getAnswer(myString:String):String {
...
return myString;
}
Specify types
Events are now more strongly typed than in Flex 1.x. As a result, you should specify the object
type in the event listener function. For example, previously you could write the following:
function myListener(event) { var s = event.type; }
Now, you must specify an event object in the function’s signature; for example:
private function myListener(event:Event):void { var s = event.type; }
Where possible, make the events as specific as possible. If the previous example was a listener
for click events, specify a MouseEvent as the type:
private function myListener(event:MouseEvent):void { ... }
Remove delegates
You are no longer required to wrap a listener function with a Delegate to maintain application
scope. You can remove the Delegate from the following line:
b1.addEventListener("click", mx.utils.Delegate.create(this,myListener));
16 Getting Started
Step 5: Import classes for package-level
functions
When you use package-level functions, you must import the package. For example, in Flex 1.x
you could call the show() method in the following way:
mx.controls.Alert.show("This is an Alert!");
In Flex 2, you must import the package before calling the function, as the following example
shows:
import mx.controls.Alert;
Alert.show("This is an Alert!");
Adobe recommends that you use unique package names so that there are no duplicate class
names in your source paths. The generally accepted syntax is to use the reverse URL
technique; for example:
com.yourcompany.MyPackage
Package names must match the directory hierarchy. For example, if you have the following
component used by your main application:
/myfiles/MainApp.mxml
/myfiles/mycomponents/TrivialComponent.mxml
For more information about the package statement syntax, see “Package statement syntax”
on page 26.
Step 8: Charts
If you are using Adobe Flex 2 SDK, you must now install a separate SWC file to use charts.
For more information, see the installation instructions in the Adobe Flex Charting’
readme.txt file.
If you are using the Flex Data Services server, charts are included.
The way charts are implemented also changed significantly. For more information, see
“Charting” on page 165.
Step 9: Overrides
Whenever a method on a subclass overrides a similarly named method on a superclass, the
declaration of the subclass’s method must now be prefixed by override. For more
information, see “Overriding a method” on page 163.
18 Getting Started
Step 10: Binding
To make a user-defined variable bindable, you must now explicitly identify it by adding the
[Bindable] metadata tag to the property; for example:
[Bindable]
public var catalog:Array;
In addition, the <mx:Binding> tag must be moved to the top level. The following example
compiled in Flex 1.5:
<mx:HBox>
<mx:Label id="myLabel"/>
<mx:Label id="my2ndLabel" text="hello"/>
<mx:Binding source="my2ndLabel.text" destination="myLabel.text"/>
</mx:HBox>
In Flex 2, you must move the tag to the top level, as the following example shows:
<mx:Binding source="my2ndLabel.text" destination="myLabel.text"/>
<mx:HBox>
<mx:Label id="myLabel"/>
<mx:Label id="my2ndLabel" text="hello"/>
</mx:HBox>
20 Getting Started
CHAPTER 2
Contents
Overview. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
Usability improvements. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
Classes and packages. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
Using external files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
Initializing variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
Typing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
Global functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
Miscellaneous . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36
Overview
This section lists some of the most common changes that you will encounter when migrating
ActionScript 2.0 to ActionScript 3.0. The remaining sections provide more details about
specific changes in the language.
■ Most classes are sealed (non-dynamic); as a result, you cannot get or set properties, or call
methods, that weren’t declared.
■ Declarations are no longer public by default.
■ You cannot get or set a property, or call a method, on an object reference which is null or
undefined.
■ Method overrides must be marked override, and the signature must match exactly.
21
■ A subclass cant have a var with the same name as one visible from the superclass, and you
can’t override a var.
■ You must declare a type for everything or you’ll get a compiler warning.
■ Accessing methods or properties of the target of an event object won't compile unless you
cast event.target to the type of the target. For example, event.target.foo must be changed
to MyComponent(event.target).foo.
■ You cannot do a for in loop on every object to see the object’s properties. This only works
on dynamic objects now. An alternative is to use E4X to do object introspection.
■ All classes must be in a package or they will only be accessible from the current script.
■ You should put return types on all of your functions.
■ Array is a final class.
■ The trace() method is now in the flash.util.trace package.
■ The Timer class in flash.util replaces setInterval and setTimeout.
Usability improvements
This section describes changes to the ActionScript language that improve usability. Most
changes described here affect the syntax but do not add functionality. This section describes
general changes to the language, and not specifics, although it includes some illustrative
examples.
The goal of these usability improvements was to provide consistency. This makes the language
easier to understand and reduces the amount of time it takes developers to learn it. The less
special case rules need to be remembered, the better.
There are some places where a better developer experience was achieved by bending the rules.
For example, ActionScript 3.0 puts enumerations into inner classes. Putting all keycode
constants into an inner class of Keyboard, however, creates too verbose a language:
Keyboard.KeyCode.UP instead of Keyboard.UP. To create a better developer experience, it
was necessary to bend the rules slightly.
Some of these changes come at the price of higher migration costs, but the longer-term
benefit is a more robust language.
Package reorganization
Some packages have been changed to make the classes within them located in a more intuitive
place. In addition, special care was taken to avoid having too many packages in the Flash
Player API. If the ActionScript packages were too granular, you would have a hard time
finding the classes you want to use. For some examples, see “Global functions” on page 34.
Accessors
Like C#, ECMAScript 4 supports using accessors. Accessors were also a feature of
ActionScript since Flash Player 6. Instead of hand-coding the getX() and setX() methods,
developers can declare a property in such a way as to be interpreted as an accessor. Getting or
setting the value of this accessor property invokes the associated get or set function.
Usability improvements 23
ActionScript 2.0 had many instances where getter and setter methods existed rather than
accessors. Now, ActionScript 3.0 uses accessors wherever possible. Unless a function has
arguments, it was converted to an accessor.
Methods that return a Boolean such as Socket.isConnected() were converted to accessors,
but retained the “is” or “has” prefix. For example, a method called methods would be
converted to the Socket.isConnected property.
Type annotations
All variables and methods now have type annotations, and those type annotations are as
precise as possible. The Object type is only used when there is no reasonable alternative, or
where attempting to strongly type the value makes the language more difficult to use. For
more information on type annotations, see “Typing” on page 32.
is a class that is not in any package, so it is only visible in the current script. If you put a class
in an unnamed package:
package { public class Foo {} }
Then you can access the class from any script. All scripts import the unnamed package by
default.
This implicitly declared that class Button was in package mx.controls. To place the Button
class in the mx.controls package in Flex 2:
package mx.controls {
public class Button extends mx.core.UIComponent {
public function Button() {
}
}
}
Access modifiers
The new internal access modifier refers to a different namespace in each package definition,
and is not defined outside of a package definition (that is, in global code).
If a class in a package isn’t marked public or private, then it defaults to internal. The class
cannot be accessed by classes in other packages; this is the same as the protected modifier in
Java. Accessing internal classes from outside of the package causes a ReferenceError at run
time.
If you do not put any namespace (public, private, internal, or user-defined) on a declaration,
the Flex compiler throws a warning.
The following table summarizes the access modifiers:
Inside a package, the default access specifier is internal. Outside of a package, the default
access specifier is public.
Class identifiers
The form ClassIdentifiers:ClassIdentifiers.Identifier has been deprecated and results in a
compile-time warning. It is equivalent to declaring the class name Identifier in the package
ClassIdentifiers. For example:
class P.A {} // ActionScript 2.0
package P { // ActionScript 3.0
class A {}
}
super()
You can only use a super() statement inside a constructor. It is a syntax error to use a
super() statement anywhere else in a program. Previous versions of ActionScript allowed
super() statements to be used anywhere in a class (except in a static method).
include
In ActionScript 2.0, the include keyword was preceded by an octothorp: #include. You now
use the keyword without the octothorp, and end the line with a semi-colon. For example:
ActionScript 2.0:
#include "../scripts/thescript.as"
ActionScript 3.0:
include "../scripts/thescript.as";
import
The import keyword lets you reference classes from other packages in your application. For
example, to use a trace() statement in your custom ActionScript class, you import the
flash.util.trace class. The import syntax is as follows:
import class;
For example:
import flash.util.trace;
You can optionally import entire packages using the wildcard syntax, as the following example
shows:
import flash.util.*;
However, best practices dictate that you only import the classes you need and not the entire
package. Doing so is better for performance and debugging.
ActionScript 3.0 uses a number of implicit imports to provide direct access to common global
functions such as trace(). In ActionScript 3.0, the number of implicit imports has been
reduced. For more information, see “Explicit imports” on page 34.
It is important to understand that you should import classes with an import statement rather
than use the full classname in your code. For example, do this:
import mx.formatters.*;
public var f:NumberFormatter = new NumberFormatter();
Embed
The Embed syntax in ActionScript is [Embed(params)], and this metadata must be used over
a variable. The variable should be of type Class; for example:
[Embed(source="holdon.mp3")]
var sndCls:Class;
public function playSound():void {
var snd:flash.media.Sound = new sndCls();
snd.play();
}
This works in a very similar way to what was implemented in Flex 1.x. The main difference is
that instead of typing the embedded variable String, you type it as Class. In addition,
instantiation relies on the new operator rather than the attachMovie() and attachSound()
methods.
In Flex 1.x, the [Embed] metadata was placed before a var, and the var received the linkage ID
that was associated with the asset. In Flex 2, you put the [Embed] metadata before a class
definition to associate the class with an asset. This change makes the linkage ID unnecessary;
instead, the asset is manifested to the object model as a class.
For backwards compatibility, the variable associated with an [Embed] can be of type String.
However, this requires you to get the class via the getDefinitionByName() method. For
example:
[Embed(source="holdon.mp3")]
var sndStr:String;
public function playSound():void {
var sndClass:Class = getDefinitionByName(sndStr);
var snd:flash.media.Sound = new sndCls();
snd.play();
}
Initializing variables
The default values of uninitialized typed variables (and arguments and properties) was always
undefined in ActionScript 2.0, and is almost never undefined in ActionScript 3.0. In
ActionScript 3.0, undefined is only for use with type Object. Other types can no longer store
the undefined value. If you assign undefined to other types, it will be coerced into null,
NaN, 0, or false.
Initializing variables 29
Default values
The following example shows the default values for variables of different types:
var dog:int; // defaults to 0
var dog:uint; // defaults to 0
var dog:Boolean;// defaults to false
var dog:Number; // defaults to NaN
var dog:Object; // defaults to undefined
var cat; // type defaults to Object, so default value is undefined
For all other classes (such as String, XML, MovieClip, Sprite, or any user-defined class), null
is the default value for uninitialized variables of that type.
var dog:String; // defaults to null
var dog:UserDefinedClass; // defaults to null
var dog:MovieClip; // defaults to null
With the exception of Object, the types with a non-null default value are the types which can
never hold null as a value. They get what a typecast of null to that type would result in.
To check for a possibly uninitialized variable, compare against the defaults described in
“Default values” on page 30. Alternatively, assign an initial, impossible value to your variable’s
declaration which you can then test against; for example:
var length:int = -1;
if (someTest())
length = 2;
if (someOtherTest())
length = 3;
if (length == -1)
length = lastResort();
and
if (!o) // ActionScript 3.0
if (o == null) // ActionScript 2.0
Because a Boolean can only be true or false, and never undefined, write the following when
checking if a Boolean is true:
if (b) // ActionScript 3.0
if (b == true) // ActionScript 2.0
if (b != false) // ActionScript 2.0
Alternately, you can use a try/catch block to catch the ReferenceError; for example:
try {
bb;
} catch(x:ReferenceError) {
print("no bb");
bb = 20;
}
The typeof keyword does not throw a ReferenceError in this case, but rather returns
undefined.
For a dynamic class such as Object, the compiler expects that instances will often have
dynamic properties added to them. The compiler does not throw a ReferenceError when
accessing an undeclared property of a variable if its value is an instance of a dynamic class; for
example:
var a:Object = new Object();
if (a.foo == undefined) // Does not throw a ReferenceError.
a.foo = 22;
About NaN
NaN (Not a Number) is a special instance of Number used to indicate a value which is outside
the range of valid Numbers. Any Boolean valued comparison involving NaN (such as ==, ===,
=>, and >) always returns false because any Number operation involving NaN is bogus. This
is exactly how C++, Java, and other languages treat NaN as well.
For comparisons with NaN, use the global isNaN() method:
var a:Number;
if (isNaN(a))
a = 22;
Initializing variables 31
If you previously checked against undefined for a Number, you use a similar syntax; for
example:
if (n == undefined) // ActionScript 2.0
if (isNaN(n)) // ActionScript 3.0
Typing
ActionScript 3.0 is more strongly typed than previous versions of ActionScript. This section
describes changes to the rules of typing.
Explicit typing
Flex 2 checks for type correctness for class and package property/methods at compile-time,
and enforces types at run time. By using stricter typing, you increase performance of your
application and strengthen the compile-time error checking.
If a variable is untyped, it will be treated as if it is type Object, which is slower than a Number,
int, uint, String, or Boolean. You should use Object only when absolutely necessary, and you
should never leave a variable untyped.
Use the most restrictive type that will work. Do not use Number if you can use int, and do
not use int if you can use uint. Use Class if something is a class reference.
In many cases, you will need to cast a general type to something more specific to get the
benefits of strong typing. Omitting types causes the Flex compiler to throw a warning, so your
applications will compile without this step.
The compiler enforces type checking wherever possible, but due to the dynamic nature of the
language, it does not checking style variable access or variables and functions declared outside
of classes (because they could be redefined dynamically at run time).
In ActionScript 3.0, type checking is performed at run time. In previous versions of
ActionScript, it was only checked at compile time. The following example shows how the
compiler will react
class a {
var b:String;
}
var c = new a();
c.b = 22; // Results in a compiler error.
c["b"] = 22; // ActionScript 2.0 would allow this, but ActionScript 3.0
// throws a TypeError exception.
The arguments assigned to method parameters must have compatible number and types.
For example:
class B {
public function B() {}
}
class A extends B {
public function A() {
super();
}
}
class Main extends MovieClip {
public function Main() {
var a:A = new A();
trace(a instanceof B); // false; instanceof is deprecated.
trace(a instanceof A); // false; instanceof is deprecated.
trace(a is B); // true
trace(a is A); // true
}
}
Primitive types
In ActionScript 3.0, there is no longer a distinction between primitive types such as strings
and instances of the String class. All strings are instances of String; every datatype is an
instance of some class. The same is true for numbers and Booleans. For example:
print("test" == String("test")); // true
print("test" === String("test")); // true
print(45 == new Number(45)); // true
print(45 === new Number(45)); // true
print("one;two;three".substring(4,7)); // "two"
print((255).toString(16)); // "ff"
Non-assignment expressions
A non-assignment expression is any expression where a value is not assigned to a property (or
a variable or argument); for example:
var myVar : hintString ? String : Number;
Typing 33
(hintString ? String:Number) is the non-assignment expression. The variable myVar is
dynamically typed to be String if hintString is true, else its type will be Number. You can
use a non-assignment expression anywhere that you would use a type-assignment expression.
Global functions
Most global functions have changed packages. In addition, they are no longer implicitly
imported. This section describes some changes to the global functions.
Explicit imports
In most cases, you must import the classes to use global functions. For example, to use
functions in the System.* package, you now import flash.system.*. The global functions in
System.* were previously accessible in your <mx:Script> blocks without explicit imports.
The following table lists common functions that you must now explicitly add an import
statement to use:
For more information on what packages global functions are in, see the global function’s entry
in ActionScript 3.0 Language Reference.
The trace() function is an exception. It is in the flash.util package, but is implicitly
imported.
int(expr) Math.round(expr)
length(expr) expr.length
mbchr(num) String.fromCharCode(num)
mblength(string) string.length
mbord(char) String(char).charCodeAt(0)
ord String(char).charCodeAt(0)
random Math.random
Deprecated features
The following features are deprecated:
■ The Object.registerClass() method no longer works on ActionScript 1.0 prototype
objects, only on ActionScript 2.0 classes.
■ Prototype inheritance no longer works for the built-in objects.
■ Features such as __resolve no longer works the same way.
■ ASNative is no longer supported.
■ #initclip no longer supported.
■ _global may not be supported (use static variables of classes).
■ Most classes are sealed, not dynamic, and cannot have properties added to them.
■ Top-level functions such as gotoAndPlay() are not supported or changed.
Global functions 35
Miscellaneous
This section describes miscellaneous changes to the ActionScript language.
MovieClip
MovieClip has been replaced by Sprite as the parent class of the base object for Flex controls,
UIComponent.
The following table lists changes to methods of MovieClip:
The drawing methods such as moveTo() are now accessed via the graphics property of the
MovieClip object. To use them you must import the flash.display.* package.
Metadata
You must now separate metadata properties with commas. For example:
ActionScript 2.0:
[Style(name="horizontalAlign" enumeration="left,center,right"
inherit="no")]
ActionScript 3.0:
[Style(name="horizontalAlign", enumeration="left,center,right",
inherit="no")]
Miscellaneous 37
Constants
You can use the const keyword to define constants in ActionScript 3.0. First, you determine
which class and instance variables qualify as constants, and then declare them with const
instead of var; for example:
static const NONMODAL:Number = Alert.NONMODAL;
const backgroundColorName:String = "buttonColor";
Method signatures
This section describes changes to method signatures in ActionScript 3.0.
No arguments
If a function takes no arguments, be sure to specify its argument list as () and not as (void).
The latter specifies a single argument of type Object named “void”. Consider which, if any, of
the arguments should be optional, and assign default values for them; for example:
override public function createClassObject(type:Class, name:String=null,
depth:int=0, initObj:Object=null):UIObject
For example:
function foo(n:Number, ... arrayOfArgs):void
The “...” and its array must be the last argument in the method. You cannot specify a type
because it is always an Array containing the other arguments.
The following example shows how to use a method with a variable number of arguments. If
you define the following:
function myfunc(arg1, ... arrayOfArgs)
ActionScript 3.0:
class A {}
var a: A = new A
trace(a.b) // Output: undefined
a.__proto__.b = 10 // Error, __proto__ unsupported.
// Use .constructor.prototype instead.
a.constructor.prototype.b = 10; // Ok
trace(a.b) // Output: 10
class C {
var x:Number = 20;
}
var c:C = new C();
a.__proto__ = C.prototype; // Error, __proto__ unsupported.
// .constructor.prototype is equivalent,
// though read only.
Primitive types
Primitive types are sealed classes and do not have object wrappers. Primitive types in
ActionScript 3.0 are final, sealed classes. Furthermore, there are no object wrappers for
primitives. As a result, you cannot create properties on them at run time; for example:
ActionScript 2.0:
newstring = new String("hello");
newstring.sayHi = function() {
trace("hi!");
}
newstring.sayHi();
newstring2 = "hello";
Miscellaneous 39
newstring2.prop = 1;
trace(newstring2.prop); // prints '1'
ActionScript 3.0:
newstring = new String("hello");
String.prototype.sayHi = function() {
trace("hi!");
}
newstring.sayHi();
newstring2 = "hello";
newstring2.prop = 1; // Warning, String is sealed...
String.prototype.prop = 1;
trace(newstring2.prop); // Output: 1
doLater() method
The doLater() method on UIComponent has been removed. You now use callLater().
The callLater() method takes a similar number of arguments. You no longer specify the
object on which the function to be called later is defined. In addition, because of stricter
typing, you must remove quotes from around the function if you used them; the type is
function and cannot be coerced from type String. For example:
Flex 1.5:
doLater(this, "moveText");
Flex 2:
callLater(moveText);
The callLater() method still takes an optional args argument. For more information, see
ActionScript 3.0 Language Reference.
LocalConnection
The LocalConnection.allowDomain() method specifies one or more domains that can send
LocalConnection calls to this LocalConnection instance. In previous versions of ActionScript,
the allowDomain() method was a callback method that you implemented. In ActionScript
3.0, allowDomain() is a built-in method of LocalConnection that you call. This makes the
allowDomain() method work in much the same way as the Security.allowDomain()
method.
Flex Classes 3
This topic describes API changes to the Flex class library in Adobe Flex 2 SDK, including
class-level changes to containers, core classes, and UI components.
Contents
Core classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
Containers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53
Controls . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61
Effects. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81
Events . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84
Formatters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89
Interfaces . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 90
Managers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91
Media controls. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 94
Printing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 94
Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95
Service tags . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95
Skins . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97
States . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 98
Utilities . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99
Validators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99
41
Core classes
The UIObject and UIComponent classes have been combined. As a result, references to the
UIObject class should be replaced by UIComponent. Visual Flex controls are subclasses of the
UIComponent class (formerly UIObject). In Flex 1.5, the UIComponent class was a
descendent of the MovieClip class. Now, the UIComponent class descends from the Sprite
class. The following example shows the full hierarchy of a Flex control, such as the Button
control:
Object
|
+--flash.events.EventDispatcher
|
+--flash.display.DisplayObject
|
+--flash.display.InteractiveObject
|
+--flash.display.FlashContainer
|
+--flash.display.Sprite
|
+--mx.core.UIComponent
|
+--mx.controls.Button
The EventDispatcher class was a mixin. It is now a base class in the flash.events package.
This section describes changes to Flex classes in the mx.core package.
mx.core.Application
The Application class now directly extends mx.core.Container instead of mx.containers.Box.
The following table describes changes to the mx.core.Application class:
42 Flex Classes
Member Change description
createLater addToCreationQueue
marginBottom paddingBottom
marginLeft paddingLeft
marginRight paddingRight
marginTop paddingTop
mx.core.Container
The class as been moved to the mx.core package.
Core classes 43
The following table describes changes to the Container class:
childIndexChanged childIndexChange
hLineScrollSize horizontalLineScrollSize
hPageScrollSize horizontalPageScrollSize
hPosition horizontalScrollPosition
hScrollBarStyleName horizontalScrollBarStyleName
44 Flex Classes
Member Change description
hScroller horizontalScroller
hScrollPolicy horizontalScrollPolicy
marginBottom paddingBottom
marginLeft paddingLeft
marginRight paddingRight
marginTop paddingTop
maxHPosition maxHorizontalScrollPosition
maxVPosition maxVerticalScrollPosition
showInAutomationHierarchy Removed.
viewMetricsAndMargins viewMetricsAndPadding
vLineScrollSize verticalLineScrollSize
vPageScrollSize verticalPageScrollSize
vPosition verticalSrollPosition
vScrollBarStyleName verticalScrollBarStyleName
vScroller verticalScroller
vScrollPolicy verticalScrollPolicy
If you set the background style, Flex ignores any value that is supplied for backgroundAlpha,
backgroundColor, backgroundImage, or backgroundSize. If you do not specify a value for
the background style, Flex uses the backgroundAlpha, backgroundColor,
backgroundImage, and backgroundSize properties, as it did in Flex 1.5. Flex displays a
deprecation warning if you use backgroundAlpha or backgroundSize.
mx.core.ContainerAllChildrenList
This class is now named ContainerRawChildrenList and is private.
mx.core.ContainerScrollPolicy
This class is now named ScrollPolicy.
Core classes 45
mx.core.MovieClipLoaderAsset
The following table describes changes to the mx.core.MovieClipLoaderAsset class:
mx.core.MXMLUIObject
The MXMLObject class is now the IMXMLObject class, to conform with the Flex 2 interface
naming style.
mx.core.Repeater
The following table describes changes to the mx.core.Repeater class:
mx.core.ScrollView
The ScrollView class is now named ScrollControlBase.
The following table describes changes to the ScrollView class:
hPosition horizontalScrollPosition
hScrollBarStyleName horizontalScrollBarStyleName
hScroller horizontalScroller
hScrollPolicy horizontalScrollPolicy
maxHPosition maxHorizontalScrollPosition
maxVPosition maxVerticalScrollPosition
vPosition verticalScrollPosition
vScrollBarStyleName verticalScrollBarStyleName
vScroller verticalScroller
vScrollPolicy verticalScrollPolicy
46 Flex Classes
mx.core.Skin*
The mx.core.Skin* classes have been renamed to use the term Asset in the class name. For
example, the SkinSprite class is now named SpriteAsset, and the SkinMovieClip class is now
named MovieClipAsset.
These classes now implement the IFlexAsset interface.
mx.core.UIComponent
The UIComponent class has been combined with UIObject to form a single base class for
visual Flex components. As a result, many of the changes listed in this section apply to
properties, methods, and other members that were originally of the UIObject class.
The following table describes changes to the mx.core.UIComponent class:
Core classes 47
Member Change description
createEmptyObject() Removed. Use the new operator and the addChild()
method or other methods to add new visual objects to the
display list.
createToolTip toolTipCreate
currentStateChanged currentStateChange
deleteStyle() clearStyle()
draw updateComplete
getSystemManager() systemManager
getUnscaledHeight() unscaledHeight
getUnscaledWidth() unscaledWidth
hideToolTip toolTipHide
invalidateStyle() styleChanged()
MAX_HEIGHT DEFAULT_MAX_HEIGHT
MAX_WIDTH DEFAULT_MAX_WIDTH
48 Flex Classes
Member Change description
mouseOverEffect rollOverEffect
mouseOutEffect rollOutEffect
notifyEffectEnding effectEnding
notifyEffectPlaying effectPlaying
popUp isPopUp
scrollTrackColor Removed.
setFocusLater() This method is now private.
setSize() setActualSize()
showToolTip toolTipShow
startToolTip toolTipStart
validationFailed validationResultHandler()
validationSucceeded() validationResultHandler()
valueCommitted valueCommit
Core classes 49
The alpha, scaleX, and scaleY properties
NO TE
This change formerly applied to the UIObject class, but because UIObject and
UIComponent have been combined into a single base class, the change now applies to
the UIComponent class.
The alpha, scaleX, and scaleY properties now range from 0 to 1 instead of from 0 to 100.
For example, to make a UIObject 50% opaque, specify alpha=0.5 instead of alpha=50. To
stretch the object horizontally by a factor of two, specify scaleX=2 instead of scaleX=200.
The default value for the focusAlpha property is now 0.3.
This change formerly applied to the UIObject class, but because UIObject and
UIComponent have been combined into a single base class, the change now applies to
the UIComponent class.
The width and height properties are now typed as Number. In Flex 1.5, you could set the
width and height to a Number (such as 50) or a String (such as "50%"). Because the type is
now only a Number, you can no longer use the following syntax in your ActionScript:
myUIObject.width = "50%";
To set widths and heights using percentage values, you must now use the following syntax:
myUIObject.percentWidth = 50;
However, in MXML, you can express the width property as a pixel or percentage value. For
example, the following two lines of code are valid:
<Canvas width="50%">
<Canvas percentWidth="50">
This change formerly applied to the UIObject class, but because UIObject and
UIComponent have been combined into a single base class, the change now applies to
the UIComponent class.
The addEventHandler() method has been removed from UIObject. This method is now
inherited from the flash.events.EventDispatcher class.
50 Flex Classes
getURL() method
NO TE
This change formerly applied to the UIObject class, but because UIObject and
UIComponent have been combined into a single base class, the change now applies to
the UIComponent class.
In Flex 1.5, every UIObject inherited the getURL() method from the MovieClip class. This is
no longer the case. You now use the navigateToURL() method in the flash.net package,
which takes a URLRequest object rather than a String for the URL:
navigateToURL(new URLRequest('url'));
This change formerly applied to the UIObject class, but because UIObject and
UIComponent have been combined into a single base class, the change now applies to
the UIComponent class.
The load event, which was previously deprecated, has been removed.
The unload event has been moved to the SWFLoader object and is dispatched whenever a
loaded SWF file is removed using the LSWFLoader.unload() method.
Drawing methods
N OT E
This change formerly applied to the UIObject class, but because UIObject and
UIComponent have been combined into a single base class, the change now applies to
the UIComponent class.
The Adobe Flash drawing API methods, such as beginFill() and moveTo(), are no longer
inherited by UIObject; they are now methods of the Graphics object, which you access with
the graphics property of Sprite, which UIObject inherits.
Core classes 51
Enumerated values are now constants
In many cases, properties that took a predefined list of values (such as the Button control’s
labelPlacement property taking right, left, bottom, and top) now take class constants as
well. For example, the labelPlacement property can now take one of the following
constants:
■ ButtonLabelPlacement.RIGHT
■ ButtonLabelPlacement.LEFT
■ ButtonLabelPlacement.BOTTOM
■ ButtonLabelPlacement.TOP
Other properties that now use constants include the Box control’s direction property; the
Container control’s creationPolicy, hScrollPolicy, and vScrollPolicy properties, and
the ProgressBar control’s direction, labelPlacement, and mode properties.
This change applies to ActionScript code. In general, the MXML usage has not changed.
life-cycle methods
The createChildren(), childrenCreated(), commitProperties(), measure(), and
updateDisplayList() methods of UIComponent are now protected rather than public.
These are component life-cycle methods that the framework calls, and which component
developers must override, but they should not be called directly.
Flex 1.x:
override public function measure():void {
...
}
Flex 2:
override protected function measure():void {
...
}
mx.core.UIObject
The UIObject base class has been merged with the UIComponent class. UIComponent is
now the lowest-level base class for nonskins. For information about changes to the combined
object, see “mx.core.UIComponent” on page 47.
52 Flex Classes
mx.core.UITextFormat
The following table describes the changes to the UITextFormat class:
mx.core.View
The mx.core.View class has been removed and its functionality has been distributed between
the SWFLoader (formerly Loader), ScrollControlBase (formerly ScrollView), and Container
classes.
Object creation and destruction methods that were on the View class have been removed. To
create a new object, you now use the new operator and use the addChild() method or other
methods to add the new object to the parent container. To destroy an object, you use the
removeChild() or other methods to remove the object from the parent container.
Containers
This section describes changes to Flex classes in the mx.containers package. In addition to the
changes listed here, there are also changes to the layouts. For more information, see Chapter
15, “Using Layout Containers,” in Flex 2 Developer’s Guide.
Containers 53
mx.containers.Accordion
The following table describes changes to the Accordion class:
headerStyle headerStyleName
historyManagement historyManagementEnabled
newValue newIndex
openEasing openEasingFunction
marginBottom paddingBottom
marginTop paddingTop
prevValue oldIndex
selectionChange change
mx.containers.accordionclasses.*
The accordionclasses package is now named accordionClasses.
54 Flex Classes
mx.containers.ApplicationControlBar
The following table describes changes to the ApplicationControlBar class:
mx.containers.Box
The following table describes the changes to the Box class:
marginTop paddingTop
mx.containers.buttonbarclasses.ButtonBarButton
This class has been moved to the mx.controls.buttonBarClasses package and is now private.
mx.containers.Canvas
The following table describes the changes to the Canvas class:
mx.containers.ControlBar
The ControlBar class now derives from mx.containers.Box instead of mx.containers.HBox.
The following table describes changes to the ControlBar class:
Containers 55
mx.containers.DividedBox
The following table describes changes to the DividedBox class:
dividerPressed dividerPress
dividerReleased dividerRelease
getDividerCount numDividers
horizontalCursor horizontalDividerCursor
verticalCursor verticalDividerCursor
mx.containers.dividedboxclasses.*
The dividedboxclasses package is now named dividedBoxClasses.
mx.containers.Form
The following table describes changes to the Form class:
marginTop paddingTop
mx.containers.FormHeading
The following table describes changes to the FormHeading class:
56 Flex Classes
mx.containers.FormItem
The following table describes changes to the FormItem class:
marginRight paddingRight
marginTop paddingTop
mx.containers.gridclasses.*
The gridclasses package is now named dataGridClasses.
mx.containers.GridRow
The GridRow class now subclasses HBox instead of Box.
mx.containers.HBox
The following table describes changes to the HBox class:
mx.containers.HDividedBox
The following table describes changes to the HDividedBox class:
mx.containers.LinkBar
The mx.containers.LinkBar class has been moved to mx.controls.LinkBar.
Containers 57
The following table describes changes to the LinkBar class:
marginBottom paddingBottom
marginTop paddingTop
strokeColor separatorColor
strokeWidth separatorWidth
mx.containers.NavBar
The mx.containers.NavBar class has been moved to mx.controls.NavBar.
The following table describes changes to the NavBar class:
"none selected" The special value for "none selected" is -1 instead of NaN.
selectedIndex The property in NavBar containers (including TabBar and
LinkBar containers) is now public and is now an int instead
of a Number. It is also now bindable.
mx.containers.Panel
Panel containers now extend mx.core.Container instead of mx.containers.Box.
The following table describes changes to the Panel class:
marginBottom paddingBottom
marginTop paddingTop
58 Flex Classes
Member Change description
modalTransparency The range for this property is now 0 to 1, instead of 0 to
100.
panelAlpha borderAlpha
panelBorderStyle roundBottomCorners
mx.containers.TabBar
The mx.containers.TabBar class has been moved to the mx.controls package. The TabBar
container now extends mx.containers.ToggleButtonBar instead of mx.containers.NavBar.
The following table describes changes to the TabBar class:
click itemClick
tabSkin tabStyleName
mx.containers.tabbarclasses.Tab
This class has been moved to the mx.controls.tabBarClasses package and is now private.
mx.containers.TabNavigator
The following table describes changes to the TabNavigator class:
Containers 59
Member Change description
getTabAt Parameter renamed from i to index.
tabSkin tabStyleName
mx.containers.Tile
The following table describes changes to the Tile class:
marginTop paddingTop
mx.containers.TitleWindow
The following table describes changes to the TitleWindow class:
In Flex 1.x, clicking on the close button (and only the close button) generated a click event.
In Flex 2, the click event is triggered when the user presses the mouse button anywhere in
the TitleWindow area. You should change your click event handler to handle a close event
instead.
mx.containers.ToggleButtonBar
The mx.containers.ToggleButtonBar class has been moved to the mx.controls package.
The following table describes changes to the ToggleButtonBar class:
unselectable alwaysToggleOnClick
60 Flex Classes
mx.containers.ViewStack
The following table describes changes to the ViewStack class:
marginBottom paddingBottom
marginTop paddingTop
When all children are removed from a ViewStack, Flex sets the selectedIndex to -1 (was
NaN). Removing children from a ViewStack container now adjusts the selectedIndex.
If a view is removed from the front (where 0 is the front-most), Flex decrements the
selectedIndex by 1 to remain pointing at the selected item. If the current view is removed,
Flex points the selectedIndex to the next view first, and then the previous view.
If there are no remaining views, Flex sets the selectedIndex property to -1.
Controls
This section describes changes to Flex classes in the mx.controls package.
mx.controls.Alert
The following table describes changes to the Alert class:
Controls 61
Member Change description
show() The show() method now has the following signature:
show(text:String, title:String=null, flags:uint=0x4,
parent:Sprite=null, closeHandler:Function=null,
iconClass:Class=null,defaultButtonFlag:uint=0x4):A
lert
mx.controls.alertclasses.*
The alertclasses package is now named alertClasses.
mx.controls.Button
The Button class no longer inherits from SimpleButton.
The following table describes changes to the Button class:
falseDisabledSkin disabledSkin
falseDownSkin downSkin
falseOverSkin overSkin
falseUpSkin upSkin
marginLeft paddingLeft
marginRight paddingRight
marginTop paddingTop
trueDownSkin selectedDownSkin
trueOverSkin selectedOverSkin
62 Flex Classes
Member Change description
trueUpSkin selectedUpSkin
version Removed.
mx.controls.ButtonBar
The following table describes changes to the ButtonBar class:
mx.controls.ButtonBarButton
The ButtonBarButton class has been made internal only.
mx.controls.CalendarLayout
The following table describes changes to the CalendarLayout class:
todayStyleDeclaration todayStyleName
Controls 63
Member Change description
upYearButton This property is now internal only.
upYearHit This property is now internal only.
weekDayStyleDeclaration weekDayStyleName
mx.controls.ColorPicker
The following table describes changes to the ColorPicker class:
marginBottom paddingBottom
marginLeft paddingLeft
marginRight paddingRight
marginTop paddingTop
openEasing openEasingFunction
mx.controls.ComboBase
The following table describes changes to the ComboBase class:
64 Flex Classes
mx.controls.ComboBox
The following table describes changes to the ComboBox class:
cellRenderer itemRenderer
dataChanged dataChange
textDisabledColor disabledColor
itemSkin itemRenderer
openEasing openEasingFunction
selectionEasing selectionEasingFunction
mx.controls.DataGrid
The DataGrid class now extends the new GridBase class, which extends the ListBase class.
The following table describes changes to the DataGrid class:
cellEditor itemEditorInstance
cellEndEdit itemEditEnd
cellFocusIn itemFocusIn
cellFocusOut itemFocusOut
cellPress Removed.
cellRenderer itemRenderer
cellRequestEdit itemEditBeginning
columnNames Removed.
editedCell editedItemRenderer
focusedCell editedItemPosition
getColumnAt() Removed.
getColumnIndex() Removed.
getColumnName() Removed.
Controls 65
Member Change description
headerColor headerColors
headerStyle headerStyleName
hGridLineColors horizontalGridLineColors
hGridLines horizontalGridLines
hPosition horizontalScrollPosition
minColWidth minColumnWidth
removeAllColumns() Removed.
removeColumnAt() Removed.
setColumnIndex Removed.
vGridLineColors verticalGridLineColors
vGridLines verticalGridLines
In Flex 2, when a DataGrid control’s width is not wide enough to show all columns, only the
first column gets smaller. This applies to DataGrid controls with a horizontal scroll policy of
true or auto. In Flex 1.5, DataGrid controls tried to squeeze in all the columns ignoring the
their minColWidth property.
mx.controls.dataGridClasses.DataGridColumn
The following table describes changes to the DataGridColumn class:
columnName dataField
editorClass itemEditor
editorProperty editorDataField
headerStyle headerStyleName
itemSkin itemRenderer
66 Flex Classes
mx.controls.dataGridClasses.DataGridListData
The following table describes changes to the DataGridListData class:
mx.controls.DateChooser
The following table describes changes to the DateChooser class:
headerStyleDeclaration headerStyleName
horizontalGap Removed.
monthDisplay This property is now internal only.
multipleSelection allowMultipleSelection
todayStyleDeclaration todayStyleName
Controls 67
Member Change description
weekDayStyleDeclaration weekDayStyleName
mx.controls.DateField
The following table describes changes to the DateField class:
formattingFunction labelFunction
headerStyleDeclaration headerStyleName
parsingFunction parseFunction
pulldown dropdown
weekDayStyleDeclaration weekDayStyleName
mx.controls.HorizontalList
The following table describes changes to the HorizontalList class:
itemWidth columnWidth
68 Flex Classes
mx.controls.HRule
The following table describes changes to the HRule class:
mx.controls.HSlider
The following table describes changes to the HSlider class:
mx.controls.Image
The following table describes changes to the Image class:
mx.controls.Label
The Label class now extends mx.core.UIComponent rather than mx.core.UIObject.
The following table describes changes to the Label class:
mx.controls.Link
The Link class is now named LinkButton.
Controls 69
mx.controls.List
The following table describes changes made to the List class:
cellEditor itemEditorInstance
cellEndEdit itemEditEnd
cellFocusIn itemFocusIn
cellFocusOut itemFocusOut
cellRequestEdit itemEditBeginning
editedCell editedItemRenderer
focusedCell editedItemPosition
mx.controls.listclasses.*
The listclasses package name has been changed to listClasses.
The class hierarchy for the list-based classes has changed, as follows:
ListBase
+-GridBase
+-DataGrid
+-List
+-Menu
+-Tree
+-TileBase
+-HorizontalList
+-TileList
A dragManager property has been added to the List classes. If you are using the drag-and-
drop operation in the List classes, you must set dragManager="DragManager" in order for
the drag-and-drop operation to work properly.
mx.controls.listclasses.DataProvider
The DataProvider class is removed. Use Collections instead.
For more information, see Chapter 4, “Data Providers,” on page 101.
70 Flex Classes
mx.controls.listclasses.ListBase
The following table describes changes to the ListBase class:
alternatingRowColors alternatingItemColors
calculateWidth measureWidthOfItems
cellRenderer itemRenderer
defaultIcon Removed.
getItemRendererForData() itemToItemRenderer()
isHighLighted isItemHighlighted
isSelected isItemSelected
itemSkin itemRenderer
itemToString itemToLabel
listItemRenderer itemRenderer
marginBottom paddingBottom
marginLeft paddingLeft
marginRight paddingRight
marginTop paddingTop
multipleSelection allowMultipleSelection
selectionEasing selectionEasingFunction
Controls 71
mx.controls.listClasses.ListCellRenderer
The ListCellRenderer class is now named ListItemRenderer.
The following table describes changes to the ListItemRenderer class:
mx.controls.listClasses.TileListItemRenderer
The following table describes changes to the TileListItemRenderer class:
mx.controls.Loader
The mx.controls.Loader class name has changed to mx.controls.SWFLoader.
The following table describes changes to the Loader class:
load() Using the load() method to load a JPEG, GIF, or PNG file
now creates an ImageSprite (containing an Image) as the
child of the SWFLoader.
Styles You can no longer set border and background color styles
on the SWFLoader control.
Adobe Flash Player 9 now dispatches ioError events when external data such as the image
cannot be loaded. The external loading code in View now listens for ioError events and
Error events and forwards them. The SWFLoader class traps these events and displays the
broken image.
72 Flex Classes
mx.controls.Menu
The following table describes changes to the Menu class:
cellRenderer listItemRenderer
change itemClick
defaultIcon Removed.
getMenuItemAt() Removed.
menuData This property is now internal.
menuItemRollOut itemRollOut
menuItemRollOver itemRollOver
popupDuration openDuration
textDisabledColor disabledColor
mx.controls.MenuBar
The following table describes changes to the MenuBar class:
getMenuBarItemAt() Removed.
labels Removed.
menuItemRollOut itemRollOut
menuItemRollOver itemRollOver
selectionDisabledColor Removed.
textDisabledColor disabledColor
textRollOverColor Removed.
textSelectedColor Removed.
useRollOver Removed.
Controls 73
mx.controls.menuclasses.*
The menuclasses package has been renamed menuClasses.
mx.controls.menuclasses.IMenuDataDescriptor
The following table describes changes to the IMenuDataDescriptor class:
setSelected() setToggled()
mx.controls.menuclasses.MenuCellRenderer
The MenuCellRenderer class is now named MenuItemRenderer.
The following table describes changes to the MenuItemRenderer class:
mx.controls.NumericStepper
The following table describes changes to the NumericStepper class:
dropShadow dropShadowEnabled
trackSkin Removed.
mx.controls.PopUpButton
The following table describes changes to the PopUpButton class:
openEasing openEasingFunction
openPopUp() open()
74 Flex Classes
Member Change description
popUpObject popUp
popUpOnMainButton openAlways
mx.controls.PopUpMenuButton
The following table describes changes to the PopUpMenuButton class:
menuItemRollOut itemRollOut
menuItemRollOver itemRollOver
popUpObject popUp
mx.controls.RadioButton
The following table describes changes to the RadioButton class:
mx.controls.RadioButtonGroup
The following table describes changes to the RadioButtonGroup class:
selectedData selectedValue
mx.controls.RichTextEditor
The following table describes changes to the RichTextEditor class:
enableToolTip showToolTips
selectedTextRange selection
Controls 75
mx.controls.richtexteditorclasses.*
The richtexteditorclasses package is now named richTextEditorClasses.
mx.controls.scrollClasses.ScrollBar
The following table describes changes to the ScrollBar class:
minPos minScrollPosition
thumbDisabledSkin Removed.
mx.controls.SimpleButton
The SimpleButton class has been removed.
mx.controls.Slider
The thumb labels, which were known as ToolTips on the Slider, HSlider, and VSlider
controls, are now known as data tips on those controls. Several property names have changed
to reflect this change. The controls now also support traditional ToolTip labels, which are
labels that appear for the entire control. You set these by using the inherited toolTip
property.
The following table describes changes to the Slider class:
minValue minimum
scrollTrackHeight Removed.
showTicks Removed. Instead of setting it to false to turn off tick
marks, you set tickInterval to 0; for example:
<mx:HSlider id="hs1" snapInterval="1"
tickInterval="0"/>
slideEasing slideEasingFunction
showValueTip showDataTip
sliderToolTipClass sliderDataTipClass
76 Flex Classes
Member Change description
snapToTicks snapInterval
thumbDragged thumbDrag
thumbPressed thumbPress
thumbReleased thumbRelease
tickHeight tickLength
tickSpacing tickOffset
toolTipFormatFunction dataTipFormatFunction
toolTipOffset dataTipOffset
toolTipPlacement dataTipPlacement
toolTipPrecision dataTipPrecision
trackHighlight showTrackHighlight
mx.controls.sliderclasses.*
The sliderclasses package is now named sliderClasses.
mx.controls.sliderclasses.SliderToolTip
The SliderToolTip class is now named SliderDataTip.
mx.controls.TextArea
The following table describes changes to the TextArea class:
hPosition horizontalScrollPosition
hScrollPolicy horizontalScrollPolicy
linkColor Removed.
maxVPosition maxVerticalScrollPosition
Controls 77
Member Change description
maxHPosition maxHorizontalScrollPosition
password displayAsPassword
underlineLink Removed.
vPosition verticalSrollPosition
vScrollPolicy verticalScrollPolicy
mx.controls.textclasses.*
The textclasses package has been renamed textClasses.
mx.controls.TextInput
The following table describes changes to the TextInput class:
dropShadow dropShadowEnabled
hPosition horizontalScrollPosition
maxHPosition maxHorizontalScrollPosition
password displayAsPassword
text You can now set the text property of a TextInput control
to null.
mx.controls.TileList
The following table describes changes to the TileList class:
itemHeight rowHeight
itemWidth columnWidth
78 Flex Classes
Flex 1.x:
<mx:TileList id="myTile" dataProvider="{dataObject}"
cellRenderer="ProdtThumbnail" itemWidth="120" itemHeight="116">
Flex 2:
<mx:TileList id="myTile" dataProvider="{dataObject}"
listItemRenderer="ProdThumbnail" columnWidth="120" rowHeight="116">
mx.controls.ToolTip
The following table describes changes to the ToolTip class:
mx.controls.Tree
The following table describes changes to the Tree class:
cellPress Removed.
defaultIcon Removed.
expandItemHandler() This method is now internal.
getNodeDisplayedAt() Removed. Use Tree.listItems[rowIndex][0].data
instead.
maxHPosition maxHorizontalScrollPosition
openEasing openEasingFunction
rootVisible showRoot
selectionDuration Removed.
selectionEasing selectionEasingFunction
Was of type Time; is now of type Function.
textDisabledColor Removed.
Controls 79
mx.controls.treeclasses.*
The treeclasses package is now named treeClasses.
mx.controls.treeclasses.DefaultDataDescriptor
The following table describes changes to the DefaultDataDescriptor class:
setSelected() setToggled()
mx.controls.treeClasses.TreeCellRenderer
The TreeCellRenderer class is now named TreeItemRenderer.
The following table describes changes to the TreeItemRenderer class:
mx.controls.VRule
The following table describes changes to the VRule class:
mx.controls.VSlider
The following table describes changes to the VSlider class:
80 Flex Classes
Member Change description
showTicks Removed. Instead of setting it to false to turn off tick
marks, you set tickInterval to 0; for example:
<mx:HSlider id="hs1" snapInterval="1"
tickInterval="0"/>
Effects
The “instance” classes (such as mx.effects.RotateInstance and mx.effects.ResizeInstance) have
been moved to the mx.effects.effectClasses package.
This section describes changes to individual effects classes. In addition to the changes listed
here, the effects architecture has changed. For more information, see Chapter 8, “Behaviors,”
on page 129.
The name property is now id.
mx.effects.AnimateProperty
The following table describes changes to the AnimateProperty class:
startValue fromValue
mx.effects.Effect
The following table describes changes to the Effect class:
effectStyles relevantStyles
endEffect() end()
listener Removed.
playEffect() Use the play() method instead. The method signature has
changed to the following:
play(targets:Array=null,
playReversedFromEnd:Boolean=false):Array
repeat repeatCount
Effects 81
mx.effects.EffectInstance
The following table describes changes to the EffectInstance class:
mx.effects.MaskEffect
The following table describes changes to the MaskEffect class:
scaleEasing scaleEasingFunction
mx.effects.Resize
The following table describes changes to the Resize class:
mx.effects.SetPropertyAction
The following table describes changes to the SetPropertyAction class:
mx.effects.SetStyleAction
The following table describes changes to the SetPropertyAction class:
82 Flex Classes
mx.effects.SoundEffect
The following table describes changes to the SoundEffect class:
mx.effects.Tween
The following table describes changes to the Tween class:
mx.effects.TweenEffect
The following table describes changes to the TweenEffect class:
tweenEndHandler tweenEnd
Effects 83
Events
All events in the mx.collections package were moved to the mx.events package.
In addition to the changes listed here, the events architecture has changed. For more
information, see Chapter 6, “Events,” on page 111.
mx.events.ChildExistenceChangedEvent
The following table describes changes to the ChildExistenceChangedEvent class:
CHILD_REMOVED CHILD_REMOVE
mx.events.CalendarLayoutChangeEvent
The following table describes changes to the CalendarLayoutChangeEvent class:
mx.events.CollectionEvent
The following table describes changes to the CollectionEvent class:
mx.events.CursorEvent
This class has been removed.
mx.events.DataGridCellRenderer
The DataGridCellRenderer class is now named DataGridItemRenderer.
The following table describes changes to the DataGridItemRenderer class:
84 Flex Classes
mx.events.DataGridEvent
The following table describes changes to the DataGridEvent class:
CELL_BEGIN_EDIT ITEM_EDIT_BEGIN
CELL_END_EDIT ITEM_EDIT_END
CELL_FOCUS_IN ITEM_FOCUS_IN
CELL_FOCUS_OUT ITEM_FOCUS_OUT
CELL_REQUEST_EDIT ITEM_EDIT_BEGINNING
CELL_PRESS Removed.
cellRenderer itemRenderer
columnName dataField
itemIndex rowIndex
itemSkin itemRenderer
mx.events.DateChooserEvent
The following table describes changes to the DateChooserEvent class:
mx.events.DividerEvent
The following table describes changes to the DividerEvent class:
DIVIDER_PRESSED DIVIDER_PRESS
DIVIDER_RELEASED DIVIDER_RELEASE
Events 85
mx.events.DropdownEvent
The following table describes changes to the DropdownEvent class:
mx.events.EventDispatcher
This class has been moved to flash.events.EventDispatcher and is no longer used as a mixin.
mx.events.FlexEvent
The following table describes changes to the FlexEvent class:
DATA_OBJECT_CHANGED DATA_CHANGE
DRAW UPDATE_COMPLETE
VALUE_COMMITED VALUE_COMMIT
mx.events.IndexChangedEvent
The following table describes changes to the IndexChangedEvent class:
mx.events.ItemClickEvent
The following table describes changes to the ItemClickEvent class:
86 Flex Classes
mx.events.ListEvent
The following table describes changes to the ListEvent class:
CELL_BEGIN_EDIT ITEM_EDIT_BEGIN
CELL_END_EDIT ITEM_EDIT_END
CELL_FOCUS_IN ITEM_FOCUS_IN
CELL_FOCUS_OUT ITEM_FOCUS_OUT
CELL_REQUEST_EDIT ITEM_EDIT_BEGINNING
cellRenderer itemRenderer
itemIndex rowIndex
itemSkin itemRenderer
mx.events.ListItemSelectEvent
The following table describes changes to the ListItemSelectEvent class:
inputType triggerEvent
itemSkin itemRenderer
mx.events.LowLevelEvents
This class has been removed.
mx.events.MenuEvent
The following table describes changes to the MenuEvent class:
change itemClick
itemSkin itemRenderer
menuItem item
Events 87
Member Change description
menuItemRollOut itemRollOut
menuItemRollOver itemRollOver
mx.events.MouseEvent
The MouseEvent class is now called FlexMouseEvent. Do not confuse this with the
flash.events.MouseEvent class, which still exists.
The following table describes changes to the mx.events.MouseEvent class:
mx.utils.events.ObjectEvent
The ObjectEvent class is now named and is moved to mx.events.PropertyChangeEvent.
mx.utils.events.ObjectEventKind
The ObjectEventKind class is now named and is moved to
mx.events.PropertyChangeEventKind.
mx.events.SliderEvent
The following table describes changes to the SliderEvent class:
newValue value
mx.events.ToolTipEvent
The following table describes changes to the ToolTipEvent class:
END_TOOL_TIP TOOL_TIP_END
HIDE_TOOL_TIP TOOL_TIP_HIDE
88 Flex Classes
Member Change description
SHOW_TOOL_TIP TOOL_TIP_SHOW
SHOWN_TOOL_TIP TOOL_TIP_SHOWN
START_TOOL_TIP TOOL_TIP_START
mx.events.TreeEvent
The following table describes changes to the TreeEvent class:
inputType triggerEvent
itemSkin itemRenderer
mx.events.UIEventDispatcher
This class has been removed.
Formatters
This section describes changes to formatters.
mx.formatters.DateFormater
The DateFormatter pattern string can contain other text in addition to pattern letters. In Flex
1.5, the pattern string had to end with a pattern letter, and text following the last pattern
letter was truncated.
In Flex 2.0, you can have additional text after the last pattern letter and that text is no longer
truncated.
mx.formatters.NumberBase
Four public properties of the mx.formatters.NumberBase class have been renamed to be
consistent with similar mx.formatters and mx.validators properties.
Formatters 89
The following table describes the changes to the NumberBase class:
dSymbolTo decimalSymbolTo
tSymbolFrom thousandsSeparatorFrom
tSymbolTo thousandsSeparatorTo
mx.formatters.SwitchSymbolFormatter
The following table describes the changes to the SwitchSymbolFormatter class:
Interfaces
The following table describes changes to Flex interfaces:
IDataObject mx.core.IDataRenderer
IFocusable mx.managers.IFocusManagerComponent
90 Flex Classes
Old name New name
IFocusManager Removed. Refer to mx.managers.FocusManager
instead.
IFocusManagerContainer mx.managers.IFocusManagerContainer
IHistoryState mx.managers.IHistoryManagerClient
IInteractionReplayer mx.automation.IAutomationReplayer
ILayoutClient mx.managers.ILayoutManagerClient
ILayoutManager mx.managers.LayoutManager
IObjectChanged mx.core.IPropertyChangeNotifier
IRecorder Removed.
IStyleable mx.styles.ISimpleStyleClient
IStyleClient mx.styles.IStyleClient
ITabGroup mx.managers.IFocusManagerGroup
ITabularData mx.automation.IAutomationTabularData
ITarget mx.logging.ILoggingTarget
IToolTipClient mx.managers.IToolTipManagerClient
ITreeDataProvider Removed.
IValidationListener mx.validators.IValidatorListener
Managers
This section describes changes to Flex classes in the mx.managers package.
mx.managers.DepthManager
This class has been removed.
Managers 91
mx.managers.DragManager
Instead of setting event.handled inside the dragEnter event listener, you must call the
DragManager.acceptDragDrop(event.target) method.
You cannot set the action property of the event object. Instead, you must call the
setFeedback() method. For example, change the following code:
event.action=DragManager.Link;
to the following:
DragManager.showFeedback(DragManager.LINK);
mx.managers.FocusManager
The following table describes changes to the FocusManager class:
mx.managers.LayoutManager
The following table describes changes to the LayoutManager class:
92 Flex Classes
mx.managers.PopUpManager
The following table describes changes to the PopUpManager class:
mx.managers.SystemManager
The SystemManager class now implements the ISystemManager interface.
The following table describes changes to the SystemManager class:
getClassByName() getDefinitionByName()
getManager() getSystemManager()
getTopLevelSystemManager() topLevelSystemManager
initializeChild() childAdded()
topMostChildrenList popupChildren
Managers 93
Media controls
This section describes changes to media controls in Flex 2.
mx.controls.MediaDisplay
The MediaDisplay control has been replaced by the mx.controls.VideoDisplay control. The
API is the same, but it does not support MP3 files.
mx.controls.MediaController
The MediaController control has been removed. Use the VideoDisplay control instead.
mx.controls.MediaPlayback
The MediaPlayback control has been removed. Use the VideoDisplay control instead.
mx.controls.VideoDisplay
This class replaces the mx.controls.MediaDisplay class. The following table describes changes
to the VideoDisplay class:
Printing
This section provides information about changes to classes in the mx.printing package.
The mx.print package is now named mx.printing.
mx.print.PrintJob
The name and package of the mx.print.PrintJob class has been changed to
mx.printing.FlexPrintJob.
94 Flex Classes
mx.print.PrintJobType
The following table describes the changes to the PrintJobType class:
WIDTH MATCH_WIDTH
Resources
This section provides information about changes to classes in the mx.resources package.
mx.resource.*
The mx.resource package is now named mx.resources.
Service tags
This section describes changes to Flex classes in the mx.servicetags package. In addition to the
changes here, the Flex data services architecture has changed. For more information, see
Chapter 9, “Data Services,” on page 135.
mx.servicetags.HTTPService
The HTTPService class was moved to mx.rpc.http.HTTPService. It now extends the
mx.rpc.AbstractInvoker class.
The following table describes changes to the HTTPService class:
The HTTPService logic has been changed to match the WebService logic. Previously,
HTTPServices raised a fault for an invalid resultFormat at send time; now, HTTPService
throws an Error as soon as an invalid value is set.
Service tags 95
mx.servicetags.RemoteObject
The RemoteObject class was moved to mx.rpc.remoting.RemoteObject. It now extends the
mx.rpc.AbstractService class.
The following table describes changes to the RemoteObject class:
All RemoteObject sources need destination entries in the flex-services.xml file. You should
now name every service and not use the actual source class as the name. All definitions of
named RemoteObjects must be moved into the flex-services.xml file.
mx.servicetags.WebService
The following table describes changes to the WebService class:
96 Flex Classes
Callback URLs
Callback URLs are no longer necessary in Flex 2. Use messaging channels with endpoint
mappings instead.
Skins
This section describes changes to Flex classes in the mx.skins package. For more information,
see “Using skinning” on page 124.
mx.skins.halo.RectBorder
This class is now named HaloBorder.
mx.skins.halo.PopUpIcon
The following table describes changes to the PopUpIcon class:
mx.skins.ProgrammaticSkin
The following table describes changes to the ProgrammaticSkin class:
updateNow() validateNow()
mx.skins.RectBorder
This class is now named mx.skins.RectangularBorder.
Skins 97
States
This section provides information about changes to classes in the mx.states package.
mx.states.AddChild
The following table describes changes to AddChild class:
mx.states.SetEventHandler
The following table describes changes to SetEventHandler class:
mx.states.SetProperty
The following table describes changes to SetProperty class:
mx.states.SetStyle
The following table describes changes to SetStyle class:
98 Flex Classes
Utilities
This section provides information about changes to classes in the mx.utils package.
mx.utils.XMLUtil
The following table describes changes to XMLUtil class:
Validators
This section provides information about changes to classes in the mx.validator package.
mx.validator.Validator
The following table describes the changes to the Validator class:
disable() enabled
disableStructure enabled
enable() enabled
enableStructure() enabled
hasErrors() Removed.
isStructureValid() validate()
isValid() validate()
Validators 99
100 Flex Classes
CHAPTER 4
Data Providers 4
This topic describes migrating data providers, including the dataProvider property of Flex
controls and the ways you access and manipulate the data represented by the dataProvider
property. For detailed information on using data providers in Flex 2, see Chapter 7, “Using
Data Providers and Collections,” in Flex 2 Developer’s Guide.
The DataProvider interface and class no longer exist and have been replaced by the collection
package hierarchy. However, you still use the dataProvider property to specify the source of
the data in a control such as DataGrid or Menu. The collection classes include methods for
manipulating the underlying data and the view of that data that is displayed in the control.
The collection package includes the following interfaces and classes:
■ IList, ICollectionView, and IViewCursor interface, and the CursorBookmark class which
you use to access and manipulate data. The ICollectionView interface can represent a
sorted or filtered subset of data without modifying the underlying data.
■ ArrayCollection class, which implements the IList and ICollectionView interface using a
backing Array.
■ XMLListCollection which implements the IList and ICollectionView interface using a
backing E4X XML object.
■ Sort, and SortField for sorting the data representation of an ICollectionView.
■ ItemResponder, for handling remote paged collections.
■ ListCollectionView, a building-block class used by XMLListCollection and
ArrayCollection.
For detailed descriptions of all interfaces and classes, see the collection package in Adobe Flex 2
Language Reference. For documentation on using the package interfaces and classes, see
Chapter 7, “Using Data Providers and Collections,” in Flex 2 Developer’s Guide.
101
The following information briefly describes major migration issues:
■ Because the DataProvider interface has been replaced by methods of the collection classes,
controls that have dataProvider properties do not include any of the DataProvider
interface methods, such as getItemAt(). Instead, you manipulate the control contents by
manipulating the object, normally a collection, that acts as the data source. You can use
the methods on the dataProvider property or on the collection object directly.
For example, you can no longer use the following line:
myList.getItemAt(index).
In this case, the dataProvider property must specify a collection object that represents the
data.
■ Do not use raw Arrays or Objects in your dataProvider property if the data provider's
values change. The control that displays the data will not get updated when the
underlying data changes. Instead, convert your provider to an ArrayCollection class, as in
the following example:
<?xml version="1.0"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" >
<mx:Script>
import mx.collections.*;
public var myArray:Array = ["MA", "ME", "MI", "MN","MO", "MS",
"MT"];
public var myICV:ICollectionView = new ArrayCollection(myArray);
</mx:Script>
<mx:ComboBox id="myCB0" dataProvider="{myICV}" />
</mx:Application>
■ If you use the DataProvider class directly in an existing application, replace it with the
ArrayCollection or XMLListCollection class. These classes are not one-for-one equivalents
to the old DataProvider class. They do not include the editField, getEditingData,
getItemID, replaceItemAt, sortItems and sortItemsBy methods. If you use any of these
methods, you must different techniques. For sorting, use the Sort class and the sort
property of the ICollectionView interface.
■ The Flex 1.5 Array class implemented the DataProvider interface methods, such as
replaceItemAt() and sortItems(). In Flex 2, there is no separate Flex Array class, only the
Flash Array class, which does not implement such methods. If you used the Array class
and its DataProvider methods, convert the Array to an ArrayCollection and use IList and
ICollectionView interface methods.
103
104 Data Providers
CHAPTER 5
Binding 5
This topic describes the steps required to convert properties in your applications to be usable
as the source for a data binding expression in Adobe Flex.
For more information binding, see Chapter 5, “Using Metadata Tags in Custom
Components,” in Creating and Extending Flex 2 Components.
Contents
About binding . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 105
Binding from a property . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 106
Binding with Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .110
About binding
In Flex 1.5, it was possible to use any public property defined as a variable or Array as the
source for a data binding expression. When a public property is the source of a data binding
expression, Flex automatically copies its value to a destination property when the value of the
source property changes.
Any property can be the destination of a data binding expression. That means you do not
have to write an special code to support the destination property of a data binding expression.
Using any property as the source for data binding is supported in Flex 2, but you must
explicitly identify the property or the property’s class as bindable using the [Bindable]
metadata tag. The property may be defined as a variable or defined by using both a setter and
a getter method. If you attempt to use a property as the source of a data binding expression,
and that property does not support binding, Flex throws a warning and does not update the
destination value of the when the source value changes.
Using Arrays and DataProviders as the source for data binding expressions in Flex 2 is not
supported and you should convert your DataProviders to use the new Collections API. For
more information, see “Binding with Arrays” on page 110.
105
The <mx:Binding> tag must be a top-level
tag
In Flex 1.5, you could place the <mx:Binding> tag in a Flex container. In Flex 2.0, the
<mx:Binding> tag must be a top-level tag in the MXML file. For example:
Flex 1.x:
<mx:HBox>
<mx:Label id="myLabel"/>
<mx:Label id="my2ndLabel" text="hello"/>
<mx:Binding source="my2ndLabel.text" destination="myLabel.text"/>
</mx:HBox>
Flex 2:
<mx:Binding source="my2ndLabel.text" destination="myLabel.text"/>
<mx:HBox>
<mx:Label id="myLabel"/>
<mx:Label id="my2ndLabel" text="hello"/>
</mx:HBox>
Although the easiest way to migrate an application that uses binding is to make all public
properties in a class support data binding, it is not necessarily the best practice to use the
[Bindable] metadata tag on an entire class. Doing this causes the compiler to generate more
code, which in turn can affect performance and increase your application’s file size.
106 Binding
The Flex compiler automatically generates an event named propertyChange for all public
properties so the properties can be used as the source of a data binding expression. In this case,
specifying the [Bindable] metadata tag with no event is the same as specifying the following:
[Bindable(event="propertyChange")]
Flex 2:
[Bindable]
public var foo:String;
The Flex compiler automatically generates an event named propertyChange for all public
properties so the properties can be used as the source of a data binding expression. In this case,
specifying the [Bindable] metadata tag with no event is the same as specifying the following:
[Bindable(event="propertyChange")]
[Bindable(event="maxFontSizeChanged")]
// Define public getter method.
public function get maxFontSize():Number {
return _maxFontSize;
}
You can omit the event name in the metadata tag, as the following example shows:
// Define private variable.
private var _maxFontSize:Number = 15;
[Bindable]
// Define public getter method.
public function get maxFontSize():Number {
return _maxFontSize;
}
The Flex compiler automatically generates an event named propertyChange. In this case,
specifying the [Bindable] metadata tag with no event is the same as specifying the following:
[Bindable(event="propertyChange")]
108 Binding
Dispatching binding events from a custom
component
To dispatch an event to trigger data binding for a property, the property’s class must either
extend EventDispatcher or implement the IEventDispatcher interface. Be sure to update the
object that is passed to the dispatchEvent() method. You must use the new Event class and
not a generic Object. For more information on converting events, see “Migrating the Event
object” on page 113.
If the class already extends EventDispatcher, you do not need to make any changes. If the class
already implements IEventDispatcher, it must implement dispatchEvent(), too. If the class
does not implement dispatchEvent(), the MXML compiler reports a warning.
If the class does not extend EventDispatcher or implement IEventDispatcher and one of your
properties is marked [Bindable] or the class is marked [Bindable], the MXML compiler
modifies the class to implement IEventDispatcher. This requires the compiler to generate the
following code for you:
■ Implements the IEventDispatcher interface.
■ Adds an addEventListener() method.
■ Adds a removeEventListener() method.
■ Adds a dispatchEvent() method.
For example, the following declaration:
class Foo {
}
110 Binding
CHAPTER 6
Events 6
This topic describes changes to the Adobe Flex 2 event model for developers who are
migrating Flex applications.
Contents
About events . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .112
Component startup life cycle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .112
Migrating the Event object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .113
Using static constants . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .114
Using function listeners . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .115
Using the EventDispatcher class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .116
Maintaining scope . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 117
Using setCapture() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 117
Keyboard events. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 117
111
About events
The following list is a general overview of the changes to the Event model. Review all event
handling in your Flex application by using these guidelines.
■ All event objects are either of type Event or a subclass of Event. You should explicitly
declare or cast them to their appropriate type.
■ Use static constants such as MouseEvent.CLICK instead of string literals for the event
type, such as “click”. For more information, see “Using static constants” on page 114.
■ Do not use object event listeners. Instead use function listeners. For more information, see
“Using function listeners” on page 115.
■ Scoping in event listeners is improved. You no longer need to pass a Delegate to maintain
scope.
■ Use the currentTarget property instead of the target property when you access the
object that is listening for the event. The target property refers to the object that
dispatched the event.
Subclasses of Event, such as MouseEvent, have all the properties of the Event object and
properties that are specific to that type of event. Choosing the most specific type possible
provides the following benefits:
■ Faster run-time performance
■ Compile-time type-checking
■ Access to event-specific properties
■ Smaller SWF file size
112 Events
Migrating the Event object
This section describes migration issues related to accessing the Event object.
You should also now cast the event.target in an event handler to an appropriate type to
avoid compile-time warnings. The new code should specify the stricter event type as a
function parameter, as the following example shows:
private function doDragExit(event:DragEvent):void {
event.target.hideDropFeedback(event);
}
If you assign the target to a stronger-typed variable, you must cast; for example:
var clickTarget:Button = Button(event.target);
When using the Event object, you are encouraged to use the most strict type possible. This
lets you access properties that are specific to the target type. For example, in a mouse click
listener, you should declare the Event of type MouseEvent rather than of type Event, as
follows:
private function myClickHandler(event:MouseEvent):void { ... }
If you use Event as the type, rather than MouseEvent, you do not have access to any properties
that are specific to the MouseEvent class.
If you use the target property of the Event object to determine which control triggered the
event, you should consider changing the target property to currentTarget. The
currentTarget property supports event bubbling and capturing, which are new in Flex 2.
During these phases, the event is actually being handled by the target’s parent containers. The
target still refers to the dispatcher of the event, but the currentTarget refers to whatever
control is currently processing a bubbling or capture event.
For example, if you have <mx:List click="..."/>, inside the click handler event.target
might be one of the rows, but event.currentTarget is a reference to the List control, which
is generally what you would expect.
Another example is what occurs when you assign a mouseDown handler on a TextInput
control. Actually, the TextField class that is inside the TextInput control dispatches the event
(depending on where the user clicked), so the TextField control, not the TextInput control, is
the target. However, the TextInput control is the currentTarget if that is where you
attached the handler.
Most controls have internal subcomponents that are often the target for mouse events.
114 Events
To find the appropriate static constant for your event type, see the events section of the
control’s entry in Adobe Flex 2 Language Reference.
You now explicitly register the custom listener’s handleEvent() method for each event you
want to handle, as follows:
public var myListener:MyEventListener = new MyEventListener();
b1.addEventListener(MouseEvent.CLICK, myListener.handleEvent);
Flex 2:
private function mouseDownHandler(event:MouseEvent):void {
var resizePanelEvent:ResizePanelEvent = new
ResizePanelEvent(ResizePanelEvent.RESIZE);
resizePanelEvent resizePanelEvent.size = "small";
dispatchEvent(event);
}
116 Events
Maintaining scope
Previously, you used the mx.utils.Delegate class to provide access to the document scope
within an event handler. You would pass the Delegate object into a call to the
addEventListener() method so that the listener would execute in that scope. This is no
longer necessary. The event listener’s scope is now the class in which it is declared as a
function, which is in most cases the scope you should expect; for example:
Flex 1.x:
addEventListener("click", mx.utils.Delegate.create(this, myListener));
Flex 2:
addEventListener(MouseEvent.CLICK, myListener);
Using setCapture()
The setCapture() method has been removed. This method was added in earlier Beta releases
of Flex 2 and was used to block events going to other (nested or non-nested) components
during drag-and-drop operations and a few other interactions. However, in the nested
situation, if one component called the setCapture() method, its parents and children could
not.
If you require this functionality, you should use the capture phase of the event model by
calling the stage.addEventListener("mouseXXX", mouseXXXHandler, true) method,
where mouseXXX is the mouse event you want to block. You can then emulate the
setCapture() method by calling the event.stopPropagation() method; however, Adobe
does not recommend doing this because most components should ignore the event.
The removeCapture() method has also been removed.
Keyboard events
The code and ascii properties of the KeyboardEvent (formerly Event) object are now
keyCode and charCode.
In drag-and-drop examples in Flex 1.x, you could use Key.isDown() to detect a key that was
pressed during the operation. In Flex 2, you use the shiftKey, ctrlKey, and altKey
properties on the KeyboardEvent object to detect keys that are pressed during the operation.
Contents
Using styles . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .119
Using skinning . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 124
Using embedded fonts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 126
Themes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 127
Using styles
There are some changes to the way you use styles. For example, the use of style properties is
now more strictly enforced. If you try to apply a style to a component that does not support
that style, Flex throws and error. Also, you cannot use the StyleManager.styles property to
change styles for entire classes in Adobe Flex Software Development Kit (SDK) 2. Finally,
some of the color value formats have changed.
This section describes these changes.
119
Using the StyleManager
When you use the StyleManager to apply styles to entire classes, you must now access the class
with the getStyleDeclaration() method. For example:
Flex 1.x:
StyleManager.styles.Button.setStyle("color","red");
Flex 2:
StyleManager.getStyleDeclaration("Button").setStyle("color","red");
You can no longer set or get styles as properties of a component or class. You now use
setStyle() and getStyle(). This also applies to using StyleManager. While accessing styles
this way was discouraged in Flex 1.5, it was not prohibited until now.
Flex 1.x:
var c = myButton.color;
StyleManager.styles.TextArea.color = "red";
Flex 2:
var c:Number = myButton.getStyle("color");
StyleManager.getStyleDeclaration("TextArea").setStyle("color","red");
In addition, you can no longer create a CSSStyleDeclaration object and then apply it to a type
of control, as the following example shows:
public var styleObj:CSSStyleDeclaration = new CSSStyleDeclaration();
styleObj.setStyle("color","red");
styleObj.setStyle("fontFamily","Tahoma");
StyleManager.styles.Accordion = styleObj;
margin-bottom padding-bottom
margin-left padding-left
margin-right padding-right
margin-top padding-top
tool-tip-offset data-tip-offset
tool-tip-precision data-tip-precision
tool-tip-placement data-tip-placement
track-highlight show-track-highlight
In Flex 2, the compiler throws an error for the borderStyle style because it’s not a valid style
on a Button control.
Using colors
The support color value formats have changed. Which format is supported depends on
whether you are setting the color in CSS or using the setStyle() method. This section
describes the valid and invalid formats.
If the format does not conform to CSS syntax, Flex throws a compiler error and the
application will not run. If the format does conform to CSS syntax but is uses invalid values,
Flex throws a run-time error.
The following are invalid color formats when you use the setStyle() method or the
StyleManager:
b5.setStyle("color",red);
b6.setStyle("color",rgb(0,255,0));
b7.setStyle("color",rgb(77%,22%,0%));
b8.setStyle("color",#66CC66);
You must include the period when you use the getStyleDeclaration() method.
Previously, properties set in type selectors that were parents of a class did not apply to that
class, unless that class was a child object in the application’s display list.
Using skinning
Previously, you defined graphical skins as symbols in a FLA file, exported the FLA file as a
SWC file from the Flash IDE, and added it to your Flex source path. The symbols in the new
SWC file replaced existing symbols in Flex component skins.
Now, all skins are specified as style properties that can be set through CSS or inline. Do not
use the symbol substitution method of defining new skins.
To use a programmatic skin, add the class to your ActionScript source path when you
compile. Then use the ClassReference() statement to reference that class in your
application’s CSS. For example, if you have MySkins/MyButtonSkin.as, you use the following
syntax to reference the class:
Button {
upSkin: ClassReference("MySkins.MyButtonSkin");
}
In Flex 2:
import flash.display.Graphics;
function updateDisplayList(...) {
var g:Graphics = graphics;
g.clear();
g.moveTo(0,0);
g.lineTo(10,10);
}
The class names of the font managers are changed from macromedia.* to flash.*.
Syntactically, you must now specify the font face in the selector or you receive a warning
similar to the following:
“An embedded font was found for family 'myFont' but it did not have the
requested plain font face.”
In Flex 2, you still use the @font-face rule to embed the font:
@font-face {
src:url("GOTHICBI.TTF");
font-style: italic;
font-weight: bold;
font-family: myFont;
}
But you then add descriptors to the class or type selector to use the embedded font face:
.myStyleBoldItalic {
font-family: myFont;
font-weight: bold;
font-style: italic;
}
Themes
You can no longer export SWC files from Flash IDE and use the symbols in that SWC as part
of a theme file in Flex. You must instead use the compc utility to compile a theme SWC file
from CSS files and graphics.
The original Halo skins are repackaged into a theme so that you can change the appearance of
your Flex applications back to the Flex 1.x look and feel.
For more information on creating and using themes, see the Flex 2 Developer’s Guide.
Themes 127
128 Styles and Skinning
CHAPTER 8
Behaviors 8
This topic describes the new architecture for behaviors in Macromedia Flex and syntax
changes from Flex 1.5. For detailed information, see Chapter 17, “Using Behaviors,” in the
Flex 2 Developer’s Guide and Chapter 15, “Creating Effects,” in Creating and Extending Flex
Components.
Contents
Overview. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 130
New Behaviors syntax. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .131
129
Overview
Flex implements effects using an architecture in which each effect is represented by two
classes:
■ Factory class Creates an object of the instance class to perform the effect on the target.
You create instances of the factory class in your application, and configure it with the
necessary properties to control the effect, such as the zoom size or effect duration. You
then assign the factory class instance to a target component, as the following example
shows:
<!-- Define factory class. -->
<mx:WipeDown id="myWD" duration="1000"/>
<!-- Assign factory class to effect targets.-->
<mx:Button id="myButton" mouseDownEffect="{myWD}"/>
<mx:Button id="myOtherButton" mouseDownEffect="{myWD}"/>
By convention, the name of a factory class is the name of the effect, such as Zoom or Fade.
■ Instance class Implements the effect logic. When an effect trigger occurs, or when you
call the play() method to invoke an effect, the factory class creates an object of the
instance class to perform the effect on the target. When the effect ends, Flex destroys the
instance object. If the effect has multiple target components, the factory class creates
multiple instance objects, one per target.
By convention, the name an instance class is the name of the effect with the suffix
Instance, such as ZoomInstance or FadeInstance.
When you use effects in your application, you are only concerned with the factory class; the
instance class is an implementation detail. However, if you want to create custom effects
classes, you must implement a factory class and an instance class. For more information, see
Chapter 15, “Creating Effects,” in the Creating and Extending Flex Components book.
130 Behaviors
New Behaviors syntax
This section describes the syntax changes to behaviors.
Flex 2:
<mx:Zoom id="small" duration="100"/>
Flex 2:
<mx:Zoom id="big" duration="100"/>
<mx:Zoom id="small" duration="100"/>
Flex 1.5:
<mx:WipeUp id="wipeup" duration="1000" show="true"/>
Flex 2:
<mx:WipeUp id="wipeup" duration="1000" showTarget="true"/>
132 Behaviors
Change to the range of several effect properties
For the Zoom, Fade and Dissolve effects, the range of the alpha, scaleX, scaleY,
zoomHeightFrom, zoomWidthFrom, zoomHeightTo, and zoomWidthTo properties have
changed. You used to set these values as percentages using integer values, where 0
corresponded to 0%, and 100 to 100%. You now specify them as decimal values, where 0.0
corresponded to 0%, and to 1.0 corresponded to 100%.
Flex 1.5:
<mx:Effect>
<mx:Zoom name="big" zoomTo="105" duration="100"/>
<mx:Zoom name="small" zoomTo="100" duration="100"/>
</mx:Effect>
Flex 2:
<mx:Zoom id="big" zoomHeightTo="1.05" zoomWidthTo="1.05"duration="100"/>
<mx:Zoom id="small" zoomHeightTo="1.0" zoomWidthTo="1.0" duration="100"/>
where:
trigger_name String indicating the name of the trigger property; for example,
mouseDownEffect or focusInEffect.
effect The effect associated with the trigger. The data type of effect is a String containing
the name of the effect, an Effect object, or an object of a subclass of the Effect class.
The getStyle() method has the following signature:
return_type getStyle("trigger_name")
where:
trigger_name String indicating the name of the trigger property.
return_type An Effect object, or an object of a subclass of the Effect class.
For detailed information, see Chapter 17, “Using Behaviors,” in the Flex 2 Developer’s Guide.
134 Behaviors
CHAPTER 9
Data Services 9
This topic describes how to migrate HTTPService, WebService, and RemoteObject
components.
Contents
About Data Services . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 135
Migrating HTTPService components . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 140
Migrating WebService components . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 143
Migrating secure data services . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 145
Mapping Java types for RemoteObject. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 150
Accessing request/response data with RemoteObject . . . . . . . . . . . . . . . . . . . . . . . 152
135
Flex 2 separates the definitions of services into a new file, services-config.xml. This file
contains definitions of the services and security constraints that were previously in the flex-
config.xml file. Optionally, it can include other configuration files by reference. The services-
config.xml file is located in the flex_deploy_dir/flex/WEB-INF/flex directory of a web
application in which you are using Flex Data Services. If you use the command-line compiler,
you must point to this file with the -services option.
The underlying architecture for communicating with the server for each type of service is
based on a new messaging framework in Flex 2. As a result, you use message channels to
communicate with the service. You configure channels in the services-config.xml file. The
new new messaging framework uses channels to connect clients to endpoints; requests are
made by sending messages over channels to endpoints of a message broker that directs the
messages to the correct service.
For information about the client-side configuration of RPC components, see Chapter 45,
“Using RPC Components,” in the Flex 2 Developer’s Guide. For information about the server-
side configuration of RPC service destinations, see Chapter 46, “Configuring RPC Services”
in the Flex 2 Developer’s Guide.
Channels
Flex now requires that you specify a channel to define the way data is transported for each
RPC service destination. Service requests and responses are now messages. Messages are sent
and received on a channel, which represents a logical connection to a destination. Channels
define a protocol and a port.
Each channel corresponds to one network transfer protocol that Flash Player supports. For
example, the AMF channel uses the AMF format over HTTP and the HTTP channel uses a
text-based format over HTTP.
Logging
The <web-service-proxy-debug>, <http-service-proxy-debug>, and <remote-
objects-debug> tags in flex-config.xml are no longer used in Flex 2. These were used for
both client-side and server-side debugging. There is no complete replacement for these. There
is a new client-side logging API; for more information, see Chapter 11, “Logging,” in Building
and Deploying Flex 2 Applications. There is also server-side logging that you can set in services-
config.xml to log Remoting Service and Proxy Service traffic; for more information, see
Chapter 43, “Configuring Data Services,”in the Flex 2 Developer’s Guide.
Unnamed RemoteObject
You can no longer use unnamed RemoteObjects. You must configure them in the
<remoting-service> section in the services-config.xml configuration file or a file that it
includes by reference. Adobe generally defines the Remoting Service in the remoting-
config.xml file, which is included by reference in the services-config.xml file.
In Flex 1.5, you could specify source="object_name" and the object’s statefulness on the
RemoteObject tag. In Flex 2, you configure the object name and its statefulness in the
configuration file.
flex-config.xml file:
<remote-objects>
<whitelist>
<unnamed>
<source>credit.*</source>
</unnamed>
</whitelist>
</remote-objects>
Flex 2 syntax
In Flex 2, every remote object must be configured as a Remoting Service destination in the
services-config.xml file, or a file that it includes by reference, such as the remoting-config.xml
file. You reference a destination in the destination property of the <mx:RemoteObject> tag.
MXML tag:
<mx:RemoteObject id="MyService" destination="SalaryEmployeeRO"/>
remoting-config.xml file:
<remoting-service>
<destination id="SampleEmployeeRO" adapter="java-object">
<properties>
<source>samples.explorer.EmployeeManager</source>
<scope>application</scope>
</properties>
</destination>
</remoting-service>
flex-config.xml file:
<remote-objects>
<whitelist>
<named>
<object name="SalaryRO">
<source>samples.explorer.SalaryManager</source>
<type>stateful-class</type>
</object>
</named>
</whitelist>
</remote-objects>
Flex 2 syntax
In Flex 2, you use the destination attribute to identify which Remoting Service destination
to use. In the configuration file, you define a destination.
MXML tag:
<mx:RemoteObject id="employeeRO" destination="SalaryEmployeeRO">
<mx:method name="getList"/>
</mx:RemoteObject>
remoting-config.xml file:
<remoting-service>
<destination id="SampleEmployeeRO">
<properties>
<source>samples.explorer.EmployeeManager</source>
<scope>session</scope>
</properties>
</destination>
</remoting-service>
You now configure HTTP services in the <proxy-service> section of the services-config.xml
file or a file that it includes by reference. Adobe generally defines the Proxy Service in the
proxy-config.xml file, which is included by reference in the services-config.xml file.
Previously, it was configured in the <http-service-proxy> section of the flex-config.xml
file.
To bind service results in Flex 2, you use the lastResult property of the service as the
binding source, as the following example shows:
<mx:Text text="{yahoo_web_search.lastResult}"/>
In Flex 1.5, the result property was the binding source.
Unnamed HTTPService
This section describes how to migrate your unnamed HTTPService tags from Flex 1.5 to
Flex 2.
For unnamed HTTPService tags that set useProxy="false", the default value, you are not
required to make any changes. These tags already ignore all server-side configuration.
flex-config.xml file:
<http-proxy>
<whitelist>
<unnamed>
<url>http://myServer.com/services/*</url>
</unnamed>
</whitelist>
</http-proxy>
Flex 2 syntax
In Flex 2, the MXML tag syntax is almost the same, but you must also set the value of the
useProxy property to true. Flex 2 does not support the protocol property that was available
in Flex 1.5; the channel defines the protocol. Flex Data Services uses either the defaultHTTP
or defaultHTTPS destination depending on whether the URL starts with HTTP or HTTPS,
respectively.
In the services-config.xml file or a file that it includes by reference, such as the proxy-
config.xml file, you add a dynamic-url to the defaultHTTP destination for an
HTTPService. The URL pattern must match the URL used in the MXML tag.
MXML tag:
<mx:HTTPService id="MyService" url="http://myServer.com/services/my.jsp"
useProxy="true"/>
proxy-config.xml file:
<destination id="defaultHTTP">
<properties>
<dynamic-url>http://myServer.com/services/*</dynamic-url>
...
</properties>
</destination>
flex-config.xml file:
<http-service-proxy>
<whitelist>
<named>
<service name="Salary">
<url>https://www.myServer.com/services/salary.jsp</url>
</service>
</named>
</whitelist>
</http-service-proxy>
Flex 2 syntax
In Flex 2, you use the destination attribute of the HTTPService tag to identify the named
service in your MXML files. You also must set the value of the useProxy property to true.
Flex 2 does not support the protocol property; the channel defines the protocol.
MXML tag:
<mx:HTTPService id="employeeHTTP" destination="Salary" useProxy="true"/>
proxy-config.xml file:
<proxy-service>
<destination id="Salary">
<properties>
<url>https://www.myServer.com/services/salary.jsp</url>
</properties>
</destination>
</proxy-service>
Unnamed WebService
This section describes how to migrate unnamed WebService tags from Flex 1.5 to Flex 2.
For unnamed WebServices tags that set useProxy="false", you are not required to make any
changes. These tags already ignore all server side configuration.
flex-config.xml file:
<web-service-proxy>
<whitelist>
<unnamed>
<url>http://myServer.com/services/*</url>
</unnamed>
</whitelist>
</web-service-proxy>
Flex 2 syntax
In Flex 2, the MXML tag syntax for an unnamed WebService is almost the same, but you
must also set the value of the useProxy property to true. Flex 2 does not support the
protocol property that was available in Flex 1.5; the channel defines the protocol. In the
configuration file, you must specify a channel and an adapter that matches the value of the
wsdl attribute.
services-config.xml file:
<destination id="defaultHTTP">
<properties>
<wsdl>{context.root}/services/ContactManagerWS?wsdl</wsdl>
<soap>{context.root}/services/ContactManagerWS</soap>
</properties>
<adapter ref="soap-proxy"/>
</destination>
Named WebService
This section describes how to migration your named WebService tags from Flex 1.5 to Flex 2.
flex-config.xml file:
<web-service-proxy>
<whitelist>
<named>
<service name="SalaryWS">
<wsdl>{context.root}/services/SalaryWS.wsdl</wsdl>
<endpoints>
<endpoint>{context.root}/services/SalaryWS</endpoint>
</endpoints>
</service>
</whitelist>
</web-service-proxy>
services-config.xml file:
<proxy-service>
<destination id="SalaryWS">
<properties>
<wsdl>{context.root}/services/SalaryWS?wsdl</wsdl>
<soap>{context.root}/services/SalaryWS</soap>
</properties>
<adapter ref="soap-proxy"/>
</destination>
</proxy-service>
Flex 2 syntax
In Flex 2, you set the remote-username and remote-password elements in the destination
definition.
services-config.xml file:
<destination id="samplesProxy">
<properties>
<url>
http://someserver/SecureService.jsp
</url>
<remote-username>johndoe</remote-username>
<remote-password>opensaysme</remote-password>
</properties>
</destination>
Alternatively, you can pass remote credentials from an RPC component in the component’s
setRemoteCredentials(remoteUsername, remotePassword) method from the client at
run time.
<security-role>
<role-name>manager</role-name>
</security-role>
<login-config>
<auth-method>BASIC</auth-method>
</login-config>
</web-app>
Flex 2 syntax
In Flex 2, you define the security constraint in the services-config.xml file:
<service-config>
<services>
... // Destinations are defined here.
</services>
<security>
<security-constraint id="sample-users">
<auth-method>Custom</auth-method>
<roles>
<role>sampleusers</role>
</roles>
</security-constraint>
</security>
</service-config>
You then refer to that security constraint in your destination definition, which is also in the
services-config.xml file or a file that it includes by reference:
<destination>
...
<security>
<security-constraint ref="sample-users"/>
</security>
</destination>
Method Description
flashgateway.Gateway.getHttpRequest() Returns the HttpServletRequest object for the
current request. Adobe recommends that you
access session data and other request data
through the getHttpRequest() method.
flashgateway.Gateway.getHttpResponse() Returns the HttpServletResponse object for the
current request.
flashgateway.Gateway.getServletConfig() Returns the ServletConfig object for the calling
servlet.
In Flex 2, this API no longer exists. The flex.messaging.FlexContext class provides equivalent
methods. Flex Data Services provides enhancements for working with session data in the
following classes:
■ flex.messaging.FlexContext
■ flex.messaging.FlexSession
■ flex.messaging.FlexSessionListener
■ flex.messaging.FlexSessionAttributeListener
■ flex.messaging.FlexSessionBindingEvent
■ flex.messaging.FlexSessionBindingListener
These classes are included in the the public Flex Data Services Javadoc documentation. For
information, see Chapter 43, “Configuring Data Services,” in the Flex 2 Developer’s Guide.
Contents
Configuration files. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 154
Security. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 155
Command-line compilers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 156
fdb debugger . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 158
153
Configuration files
The Flex server relied on configuration files in the WEB-INF/flex directory. The following
table describes changes to those configuration files:
flex-config.xml Configures Flex. You use this file This file now contains only
to define debugging, compiler, compiler settings.
cache, proxy, logging, font and
other settings for Flex.
gateway-config.xml Configures the Adobe Flash Not in Flex 2. The settings have
Remoting gateway. You can been move to the services-
configure service adapters, config.xml file.
security, logging, and other For more information, see
settings for Flash Remoting using Chapter 9, “Data Services,” on
this file. page 135.
global.css Defines default styles used This file has been replaced with
across all Flex applications. the defaults.css file inside the
frameworks.swc file. It is not
intended for developers to edit,
but can be used as a template
from which to define custom
themes.
Security
This section describes changes to Flex security.
Flex changes
You do not define the security of web services and other data services in the flex-config.xml
file. You now define them in the services-config.xml and related files.
ActionScript changes
The following general changes were made to ActionScript:
■ The System.security.* package is now named Security.*.
■ The Security.allowDomain() and Security.allowInsecureDomain() methods no
longer open up all SWF files in the caller’s domain; instead they now affect only the
calling SWF file itself.
■ Setting Security.exactSettings no longer affects all SWF files in the caller’s domain; instead
it now affects only the calling SWF file itself.
■ The LocalConnection allowDomain() and allowInsecureDomain() methods are no
longer callback methods for authors to define; instead they are now built-in methods for
authors to call, and follow the same semantics as the Security.allowDomain() and
Security.allowInsecureDomain() methods.
■ When you use XMLSocket.connect to contact a server outside a SWF file’s own domain,
the default policy file location is no longer on an HTTP server in the same domain;
instead it is now an XMLSocket policy file obtained from the same port as the main
connection attempt. You can use the Security.loadPolicyFile() method to override
this default location in the same way you used it in Flex 1.5.
Security 155
Command-line compilers
The mxmlc and compc compilers are changed for Flex 2. This section describes these changes.
mxmlc
The mxmlc utility compiles SWF files from your MXML and ActionScript files. The mxmlc
options that are no longer available include the following:
■ batch
■ contextroot
■ encoding
■ genlibdir
■ headless
■ loglevel
■ profile
■ file-specs
■ systemclasses
■ version
■ webroot
The names of many mxmlc command-line compiler options were changed to be more
consistent or descriptive. The changes include the following:
configuration config
debugpassword debug-password
global-css-url defaults-css-url
usenetwork use-network
In addition, because the data services subsystem changed, mxmlc no longer takes the
following options:
■ gatewayurl
■ gatewayhttpsurl
■ proxyurl
■ proxyhttpsurl
■ proxyallowurloverride
■ remoteallowurloverride
■ webserviceproxydebug
The maximum value for the default-script-limits option is now 60 seconds. This option
did not impose a maximum value in Flex 1.x.
The file-specs option has been removed. You do not need to specify -file-
specs=filename.mxml because it is the default option. If the last option uses a space-
separated list, you can terminate the list with -- before adding the MXML file name; for
example:
mxmlc -option arg1 arg2 arg3 -- MyApp.mxml
For a complete list of the mxmlc options, see Building and Deploying Flex 2 Applications.
compc
The compc utility compiles SWC files. The compc parameters have changed significantly. For
usage information, see the command-line help or the Building and Deploying Flex 2
Applications.
SWC files created by the Flex 1.x compiler or by previous versions of Flash do not work in
Flex 2. If you try to use a SWC file that was generated by an earlier version of compc or
output from the Flash IDE, Flex displays a compiler error similar to the following:
Unable to parse SWC catalog for C:\JRun4\servers\flex2\flex\WEB-
INF\flex\user_classes\ModalText.swc: Unknown element in swc section in
catalog.xml: componentPackage
SWD files
The fdb debugger no longer uses SWD files. Instead, Flex generates debuggable SWF files by
using the debug option with the mxmlc and compc command line compilers. There is no
longer a framework_debug.swc file. All the debug logic is built into the framework.swc.
Breakpoints
This section describes changes to breakpoints for Flex 2.
Deferred breakpoints
The fdb utility now supports deferred breakpoints. What this means is that if you try to set a
breakpoint, and the breakpoint location that you specified seems to indicate a filename or
function name that is not yet loaded into the Flash player, the fdb no longer reports an error;
instead, it remembers the breakpoint. If Flash Player eventually loads a movie that has code
from the source file that was specified in the earlier break command, fdb adds the breakpoint.
print command
Flex 2 includes the following changes to the output of the print command:
■ If a member of an object is an integer, its value is printed in both decimal and
hexadecimal.
■ If set $displayattributes was specified before the print command is executed, the
list of attributes that are displayed is different. The new list of attributes is:
■ dont_enumerate
■ read_only
■ local
■ argument
■ getter
■ setter
■ dynamic
■ static
■ private
■ public
■ internal
■ has_namespace
Customizing Components 11
This topic describes modifications to the process of creating components in ActionScript in
Adobe Flex.
This topic only contains an overview of the major changes to the process from Flex 1.5 to Flex
2.0. For detailed information on creating custom components, see Creating and Extending
Flex 2 Components.
Contents
UIObject class removed . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .161
Class variables changed . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .161
Specifying the package. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 162
Defining the class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 162
Defining the constructor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 162
Creating bindable properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 162
Overriding a method . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 163
Clip parameters removed . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 163
Initialization sequence changed . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 163
Renamed invalidateStyle() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 163
161
Specifying the package
Define your custom components within an ActionScript package. The package reflects the
directory location of your component within the directory structure of your application.
package myComponents
{
// Class definition goes here.
}
By convention, setters should use the identifier value for their argument.
3. createChildren()
4. commitProperties()
5. measure()
6. layoutChildren()
7. draw()
In Flex 2.0, the init() method has been removed, and the new updateDisplayList()
method replaces the layoutChildren() and draw() methods. You can move logic that was
formerly in the init() method to the constructor. For a complete description of the
initialization sequence for Flex 2, see Chapter 10, “Creating Advanced Visual Components in
ActionScript,” in Creating and Extending Flex 2 Components.
Renamed invalidateStyle()
The invalidateStyle() method has been renamed to styleChanged().
Contents
HistoryManager . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 165
Charting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 165
Cell renderers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 169
Validators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 170
Embedding resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 172
HistoryManager
To migrate applications from Flex 1.5 to Flex 2, your application must implement the
mx.core.IHistoryState interface; for example:
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
implements="mx.core.IHistoryState">
Also, you must declare the saveState() and loadState() methods as public. Otherwise,
they are not visible to the HistoryManager.
Charting
Flex Charting have undergone major changes for Flex 2. This section describes some
migration issues for charts for Flex 2.
Charting classes rely heavily on DataProviders and Arrays. Changes to these classes are
described throughout this document.
The name property on chart series and chart axes is now displayName.
165
Skins
Skins are now called renderers. For example, the CandlestickSkin class is now
CandlestickRenderer.
Renderers
Some functionality for the AxisRenderer was moved to other axis objects.
The labelFunction property, which was a property of AxisRenderer, is now a property of the
axis type (such as CategoryAxis). The signature for the function is changed as well. Instead of
a single parameter, the labelFunction() function now takes up to four. The new signature
is as follows:
labelFunction(categoryValue:Object, previousCategoryValue:Object,
axis:axis_type, categoryItem:Object);
For more information on using the labelFunction property, see the Flex 2 Developer’s Guide.
The title property was also moved to the individual axis rather than the axis renderer. For
example, in Flex 1.x you defined both the horizontalAxis and the horizontalAxisRenderer, as
the following example shows:
<mx:horizontalAxis>
<mx:CategoryAxis dataProvider="{expenses}" categoryField="Month"/>
</mx:horizontalAxis>
<mx:horizontalAxisRenderer>
<mx:AxisRenderer title="Expenses" labelFunction="defineLabel"/>
</mx:horizontalAxisRenderer>
In Flex 2, you set the title and labelFunction properties on the horizontalAxis:
<mx:horizontalAxis>
<mx:CategoryAxis dataProvider="{expenses}" categoryField="Month"
title="Expenses" labelFunction="defineLabel"/>
</mx:horizontalAxis>
You no longer use renderers to change the appearance of ChartItems. In Flex 1.x, for example,
you could specify a CrossRenderer or TriangleRenderer to draw a ChartItem as a cross or a
triangle:
<mx:PlotSeries>
<mx:renderer>
<mx:CrossRenderer/>
</mx:renderer>
</mx:PlotSeries>
In addition, you can no longer use the AssetRenderer to use graphics in your charts. Instead,
you must use a class that implements the IDataObject interface.
Binding
In many cases, you declare a data provider object and bind the chart to that data provider. In
Flex 2, you must add the [Bindable] metadata tag to the variable declaration, otherwise Flex
does not bind to the data. For example:
<mx:Script>
[Bindable] // Add this in Flex 2
public var expenses:Object = [{ ... }, { ... }, { ... }];
</mx:Script>
<mx:BubbleChart maxRadius="50" dataProvider="{expenses}"
mouseDown events
In Flex 1.5, mouseDown events included hitData structures, even if no data was under the
mouse’s pointer. In this case, the hitData property existed, but it was null. This behavior was
a way to check for the existence of a click on a chart control.
In Flex 2, mouseDown events do not include the hitData structure unless the mouse is
positioned over a data point. Instead, you must use the mouseDownData event.
alpha
All aspects of charting that used an alpha property to represent transparency, such as Strokes
and Fills, now use 0 to 1 for a range of values rather than 1 to 100. For example:
Flex 1.x:
<mx:SolidColor color="0x7EAEFF" alpha="30"/>
Flex 2:
<mx:SolidColor color="0x7EAEFF" alpha=".3"/>
Charting 167
Legends
You now enclose the data provider for Legend controls in curley braces; for example:
Flex 1.x:
<mx:LineChart id="linechart">
...
</mx:LineChart>
<mx:Legend dataProvider="linechart"/>
Flex 2:
<mx:LineChart id="linechart">
...
</mx:LineChart>
<mx:Legend dataProvider="{linechart}"/>
Interfaces
All chart interfaces now follow the I* naming scheme, as the following table shows:
WedgeRenderer IWedgeRenderer
LineRenderer ILineRenderer
Fill IFill
Axis IAxis
In Flex 2, cell renderers and cell editors were renamed to item renderers and item editors. In
addition, the architecture was completely redesigned for Flex 2. For more information, see
Chapter 21, “Using Item Renderers and Item Editors,” in the Flex 2 Developer’s Guide.
In Flex 2, cell renderers receive a data property that contains the data for the item to render.
For example, for a cell of a DataGrid control, the data property contains a copy of the data
provider element for the entire row of the grid. You access the data property in your cell
renderer to initialize it, as the following example shows:
<mx:VBox xmlns:mx="http://www.adobe.com/2006/mxml" width="198"
backgroundAlpha="0">
<mx:HBox height="100%">
<mx:Image id="myImage" source="{data.imageLocal}" width="30"/>
<mx:Text text="{data.displayText}" width="150" height="100%"/>
</mx:HBox>
<mx:CheckBox label="Check" selected="{data.status}"/>
<mx:TextInput selected="{data.moreText}"/>
</mx:VBox>
In this example, you use data binding to set the values of the controls in the cell renderer,
where the fields of the data property correspond to fields of the data provider that populates
the DataGrid control.
<!-- Define the TextInput control for entering the phone number. -->
<mx:TextInput id="phoneInput"/>
In Flex 2, validators are triggered by default by the valueCommit event, and you use data
binding to assign it to the interface control rather than to a model. The source property
specifies the name of the control, and the property property specifies the field of the control
to validate, as the following example shows:
<!-- Define the PhoneNumberValidator. -->
<mx:PhoneNumberValidator id="pnV" source="{phoneInput}" property="text" />
<!-- Define the TextInput control for entering the phone number. -->
<mx:TextInput id="phoneInput"/>
You can also use the validate() method of the validator to trigger a validator
programmatically. All validator classes now include a validate() method.
Styles
When you change a validator’s error message style, you must now use a class selector rather
than a type selector. You do this by prepending a period to the errorTip style as the following
example shows:
<mx:Style>
// ErrorTip { borderColor: #00FFFF } // Flex 1.5
.errorTip { borderColor: #00FFFF } // Flex 2
</mx:Style>
Validators 171
Embedding resources
In Flex 1.5, embedded resources were bound to Strings that were used to reference the
individual images by name. Although the preferred method of embedding resources in Flex 2
uses Class variables, you can still use String variables for some level of backward compatibility.
However, the various objects and tags that use your embedded assets expect them to be tied to
Class variables, so you need to use the getDefinitionByName() method to cast your string
variables. You also still need to use the [Bindable] metadata tag to declare the string variable
bindable.
For instance, the following application uses string variables and casting to display an
embedded image:
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:Script>
<![CDATA[
[Embed(source="logo.gif")]
[Bindable]
public var imgStr:String;
]]>
</mx:Script>
<mx:Image source="{getDefinitionByName(imgStr)}"/>
</mx:Application>
Although this method works, Adobe recommends that you use Class variables instead. The
equivalent application, using a Class variable, is simpler:
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:Script>
<![CDATA[
[Embed(source="logo.gif")]
[Bindable]
public var imgCls:Class;
]]>
</mx:Script>
<mx:Image source="{imgCls}"/>
</mx:Application>
Alternatively, when you use MXML, this becomes a one line application:
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:Image source="@Embed(source='logo.gif')" />
</mx:Application>
For more information, see Chapter 30, “Embedding Assets,” in the Flex 2 Developer’s Guide.
Migration Patterns 13
This topic describes some common patterns in migrating ActionScript in Adobe Flex
applications.
Contents
Instantiating Flex controls. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 174
Using mixins. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 175
Variable enumeration and object introspection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 176
Using the drag-and-drop feature . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 178
Using Timer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 182
Using the Preloader . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 183
Accessing request data. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 183
173
Instantiating Flex controls
In Flex 1.x, you created a Flex control in ActionScript by first including a reference to that
control, and then using the createEmptyObject(), createChild(), createChildren(),
createChildAtDepth(), or createClassChildAtDepth() method.
These methods were removed. In Flex 2, you use the new operator to create child controls and
attach the control to a container with the addChild() or addChildAt() method. For
example:
Flex 1.x:
var b:Button;
b = Button(createChild(Button, undefined, { label: "OK" }));
Flex 2:
var b:Button = new Button();
b.label = "OK";
addChild(b);
Similarly, in Flex 2 you would destroy the object with the destroyObject(),
destroyChild(), destroyChildAt(), or destroyAllChildren() method. These methods
are also deprecated. Instead, you use the removeChild() or removeChildAt() method.
The createComponent() method now takes only a descriptor as its first argument, rather
than either a descriptor or a descriptor index. If you know the index, use
childDescriptors[i] to get the descriptor itself.
For more information on creating and destroying Flex controls in ActionScript, see the Flex 2
Developer’s Guide.
or this:
dataGridInstance.doSomething = myFunction
You can still declare a Function type property on an Object and then supply an
implementation of that function later. For example:
class MyButton extends Button {
var doSomething:Function;
public function processInput(condition:Boolean):void {
if (condition)
doSomething();
}
}
and then:
var b:MyButton = new MyButton();
b.doSomething = function () { ... };
b.processInput(true);
You can also apply mixins to dynamic classes without their prior knowledge, as the following
example shows:
dynamic class MyButton extends Button {
...
}
and then:
// You can mix in any function onto an instance of a dynamic class:
var b:MyButton = new MyButton();
b.anyFunctionNameYouCanImagine = function () { ... };
The only class in the Flex class library that is dynamic is the Object class. In most cases, you
must create your own class.
The output displays accessors, variables, and methods of the Button control, and appears
similar to the following:
Class mx.controls::Button
...
Variable id=button1 (String)
Variable __width=66 (Number)
Variable layoutWidth=66 (Number)
Variable __height=22 (Number)
Variable layoutHeight=22 (Number)
...
Property label=Submit (String)
Property enabled=true (Boolean)
Property numChildren=2 (uint)
Property enabled=true (Boolean)
Property visible=true (Boolean)
Property toolTip=null (String)
...
Method dispatchEvent():Boolean
Method hasEventListener():Boolean
Method layoutContents():void
Method getInheritingStyle():Object
Method getNonInheritingStyle():Object
Detecting keys
Because ActionScript no longer has a Key class, and the Keyboard class replaces a limited set
of the Key class’s functionality, three new Boolean properties, ctrlKey, shiftKey, and
AltKey, were added to the DragEvent object. The new properties represent these keys’ states
when the user drags an item over a drop target. Typically, when a user holds the Shift,
Control, or Alt key down during a drag-and-drop operation, the user wants to change the
default behavior of the dragged item.
The following example checks if the user is pressing the Control key when dragging over the
target (to copy data), and sets the action in the DragManager to reflect its state.
Flex 1.5:
private function doDragOver(event:Event) {
event.target.showDropFeedback(event);
if (Key.isDown(Key.CONTROL)) {
...
} else if (Key.isDown(Key.SHIFT)) {
...
}
}
Flex 2:
private function doDragOver(event:DragEvent) {
event.target.showDropFeedback(event);
if (event.ctrlKey) {
...
} else if (event.shiftKey) {
...
}
}
Setting actions
You no longer set the action property of the event object. Instead, you must call the
DragManager.setFeedback() method, as the following example shows.
Flex 1.5:
private function doDragOver(event:Event):Void {
// If the Control key is down, show the COPY drag feedback appearance.
if (event.ctrlKey) {
event.action = DragManager.COPY;
} else {
event.action = DragManager.MOVE;
}
}
Flex 2:
private function doDragOver(event:DragEvent):void {
// If the Control key is down, show the COPY drag feedback appearance.
if (event.ctrlKey) {
DragManager.showFeedback(DragManager.COPY);
} else {
DragManager.showFeedback(DragManager.MOVE);
}
}
You can also use the reset() method rather than the stop() method to stop the timer. The
difference between stop() and reset() is that stop() stops the timer but does not reset its
count, while reset() both stops and resets.
The way in which you access these variables is changed. In Flex 1.x, you could access the
values of flashVars variables by declaring a public global variable of the same name. Using
the previous example, you could access the values of the firstname, middlename, and
lastname variables in your Flex application by just declaring them, as the following example
shows:
<mx:Script>
var firstname; // Initialized to "Nick”.
var middlename; // Initialized to "D”.
var lastname; // Initialized to "Danger”.
</mx:Script>