Macromedia FLEX-GETTING STARTED WITH FLEX User Manual

Getting Started with Flex
Trademarks
ActiveEdit, ActiveTest, Add Life to the Web, Afterburner, Aftershock, Andromedia, Allaire, Animation PowerPack, Aria, Attain, Authorware, Authorware Star, Backstage, Blue Sky Software, Blue Sky, Breeze, Bright Tiger, Captivate, Clustercats, ColdFusion, Contents Tab Composer, Contribute, Design In Motion, Director, Dream Templates, Dreamweaver, Drumbeat 2000, EDJE, EJIPT, Extreme 3D, Fireworks, Flash, FlashHelp, Flash Lite, FlashPaper, Flex, Flex Builder, Fontographer, FreeHand, Generator, Help To Source, HomeSite, Hotspot Studio, HTML Help Studio, JFusion, JRun, Kawa, Know Your Site, Knowledge Objects, Knowledge Stream, Knowledge Track, LikeMinds, Lingo, Live Effects, MacRecorder Logo and Design, Macromedia, Macromedia Action!, Macromedia Central, Macromedia Flash, Macromedia M Logo and Design, Macromedia Spectra, Macromedia xRes Logo and Design, MacroModel, Made with Macromedia, Made with Macromedia Logo and Design, MAGIC Logo and Design, Mediamaker, Movie Critic, Open Sesame!, RoboDemo, RoboEngine JFusion, RoboHelp, RoboHelp Office, RoboInfo, RoboInsight, RoboPDF, 1-Step RoboPDF, RoboFlash, RoboLinker, RoboScreenCapture, ReSize, Roundtrip, Roundtrip HTML, Shockwave, Sitespring, Smart Publishing Wizard, Software Video Camera, SoundEdit, Titlemaker, UltraDev, Web Design 101, what the web can be, WinHelp, WinHelp 2000, WinHelp BugHunter, WinHelp Find+, WinHelp Graphics Locator, WinHelp Hyperviewer, WinHelp Inspector, and Xtra are either registered trademarks or trademarks of Macromedia, Inc. and may be registered in the United States or in other jurisdictions including internationally. Other product names, logos, designs, titles, words, or phrases mentioned within this publication may be trademarks, service marks, or trade names of Macromedia, Inc. or other entities and may be registered in certain jurisdictions including internationally.
Third-Party Information
This guide contains links to third-party websites that are not under the control of Macromedia, and Macromedia is not responsible for the content on any linked site. If you access a third-party website mentioned in this guide, then you do so at your own risk. Macromedia provides these links only as a convenience, and the inclusion of the link does not imply that Macromedia endorses or accepts any responsibility for the content on those third-party sites.
Copyright © 2004 Macromedia, Inc. All rights reserved. This manual may not be copied, photocopied, reproduced, translated, or converted to any electronic or machine-readable form in whole or in part without prior written approval of Macromedia, Inc. Part Number ZFE15M400
Acknowledgments
Project Management: Stephen M. Gilson
Writing: Matthew J. Horn, Mike Peterson
Editing: Linda Adler, Noreen Maher
Production Management: Patrice O’Neill
Media Design and Production: Adam Barnett, John Francis
First Edition: November 2004 Macromedia, Inc.
600 Townsend St. San Francisco, CA 94103

CONTENTS

INTRODUCTION: About Flex Documentation . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
Using this manual . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
Accessing the Flex documentation. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
CHAPTER 1: Introducing Flex . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
About Flex. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
Developing applications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
The Flex programming model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
Features of Flex . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
Where to next . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
CHAPTER 2: Using MXML . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
About MXML. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
Basic MXML syntax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
How MXML relates to standards. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
CHAPTER 3: Using ActionScript . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43
About ActionScript . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43
Using ActionScript in Flex applications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46
Creating ActionScript components . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53
Techniques for separating ActionScript from MXML . . . . . . . . . . . . . . . . . . . . . . 54
CHAPTER 4: Architecting Flex Applications. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57
About the Flex coding process . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58
Working with a multitier application model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62
Improving application start-up time and performance. . . . . . . . . . . . . . . . . . . . . . 67
Architecting an application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70
Summary of Flex application features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79
INDEX . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83
3
4 Contents
INTRODUCTION

About Flex Documentation

Getting Started with Flex provides an introduction to Macromedia Flex. This book is intended for application developers who are new to Flex and require an overview of Flex features and capabilities.

Contents

Using this manual . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
Accessing the Flex documentation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6

Using this manual

This manual can help anyone get started with developing Flex applications. After reading this manual, you should read Developing Flex Applications for detailed information about Flex features and information about creating Flex applications.
Getting Started with Flex contains the following chapters:
Chapter Description
Chapter 1, “Introducing Flex” Introduces the Flex presentation server, a development
Chapter 2, “Using MXML” Describes MXML, the XML language for writing
Chapter 3, “Using ActionScript” Introduces ActionScript and explains how to use
Chapter 4, “Architecting Flex Applications” Describes the Flex development process. It describes
and runtime environment that lets you create rich interfaces for your web applications.
applications, and how developers use it to create applications.
ActionScript in an MXML application. Developers can use ActionScript to extend the functionality of their Flex applications.
coding practices, multitier applications, and application architecture.
5

Accessing the Flex documentation

The Flex documentation is designed to provide support for the complete spectrum of participants.

Documentation set

The Flex documentation set includes the following manuals:
Book Description
Developing Flex Applications Describes how to develop your dynamic web
applications.
Getting Started with Flex Contains an overview of Flex features and application
Flex ActionScript and MXML API Reference Provides descriptions, syntax, usage, and code

Viewing online documentation

All Flex documentation is available online in HTML and Adobe Acrobat Portable Document Format (PDF) files. Go to the documentation home page for Flex on the Macromedia website:
www.macromedia.com/go/flex15_documentation.
development procedures.
examples for the Flex API.
6 Introduction: About Flex Documentation
CHAPTER 1

Introducing Flex

This chapter introduces you to the Macromedia Flex presentation server, a development and runtime environment that lets you create rich interfaces for your web applications. Macromedia Flex defines a standards-based programming methodology for building the presentation tier of rich Internet applications. Rich Internet applications combine the responsiveness and richness of desktop software with the broad reach of web applications to deliver a more effective user experience.
This chapter describes the characteristics of a typical Flex application, provides an overview of the Flex feature set, and defines the development process that you use to create Flex applications.

Contents

About Flex . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
Developing applications. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
The Flex programming model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
Features of Flex . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
Where to next . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20

About Flex

Flex defines a development and runtime environment that lets developers familiar with server­side technologies build rich front ends for applications that take advantage of Macromedia Flash Player. While executing in Flash Player, your application can interact with server-side functionality, such as databases, web services, Java objects, and other server-side services.
Flex brings the power of Flash to developers who are familiar with traditional programming languages and server-side development environments. In Flex, you use a standards-based programming model to develop an application, describe the user interface, configure user­interface controls, and define data bindings.
7

Using Flex in an n-tier application model

By definition, enterprise applications are multitiered, where each tier brings specific benefits to the application design. A tiered architecture provides natural access points for integration with existing and future systems.
Each tier serves a specific purpose, and lets you divide the functionality of a business application into discrete components that you can implement independently from each other. For example, the following figure shows the tiers of a five-tier application model:
Client Tier
Application clients, Flash, applets, and other GUIs
Presentation Tier
ASP, JSP, Servlets, and other UI elements
Business Tier
Connects to business objects
Integration Tier
Connects to data and legacy systems
Resource Tier
Databases, external systems, and legacy resources
Running on client
Running on server
An n-tier architecture offers the following advantages:
The tiers, or even components of the tiers, can be distributed across multiple hardware systems
to improve system scalability and performance.
The client and presentation tiers shield clients from the complexities of accessing the enterprise
data store.
You can distribute application development across your development group. For example, JSP
developers are typically concerned with information presentation rather than with implementing business rules. Conversely, EJB developers are concerned with data access and manipulation, but not with presentation.
In traditional n-tier applications, the presentation tier logic executes on the server, so every client interaction requires a data transfer between the client and server.
8 Chapter 1: Introducing Flex
Flex adds new functionality and options to the n-tier model. The following figure shows the same five tiers for a Flex application:
Flash Player running Flex applications
HTTP/SOAP/AMF
Flex server
Web services
J2EE server/servlet container
Java BeansEJBs
Client and presentation tiers running on the client
Business and integration tiers
Resource tier
In Flex, Flash Player provides the platform for interface development so that both client and presentation tier logic executes on the client computer. Flex applications that execute in Flash Player process user interactions; perform data validation; issue HTTP, SOAP, AMF requests; and perform other operations previously performed on the server. Because Flash Player runs consistently across all major operating systems and browsers, you do not have to program your applications for a specific browser or platform.
Note: You can still develop presentation-tier logic for the server as part of your application, and connect to that logic from the client.
The Flex server executes on a J2EE platform or servlet container, and provides the integration point for Flex applications to server-side functionality. The Flex server also includes the Flex compiler, caching mechanism, and web service proxy.
You do not need to modify the business and integration tiers to integrate with Flex. This means that you code the business and back-end functionality in the same way you did for your existing applications. Flex lets you connect to your back-end systems and application logic using web services, HTTP, EJBs, or other methods.

Benefits of using Flex

Historically, most Internet application interfaces are built in HTML. Because HTML applications are page-based, they demand complete page refreshes when information is submitted to a server, as well as when a client navigates from one page to another. Each page load uses network bandwidth and server resources. In addition, application logic typically executes on the server rather than on the client, which requires a server request and response to process any data.
About Flex 9
Applications running in Flash Player behave like desktop applications, instead of a series of linked pages. Flash Player manages the client interface as a single, uninterrupted flow and does not require a page load from the server when the client moves from one section of the application to another.
Flex offers the following additional benefits to your web applications:
Standards-based architecture Macromedia designed Flex, ActionScript, and MXML, the
Flex scripting language, to existing standards. MXML is XML-compliant, implements styles based on the Cascading Style Sheets, level 1(CSS1) specification, and implements an event model based on a subset of the W3C DOM Level 3 Events specification. ActionScript is an ECMAScript-based language that provides support for object-oriented development. The Flex server executes on standard J2EE platforms or servlet containers.
Reduction in server load and network bandwidth Some or all of the presentation tier of a Flex
application runs in Flash Player, which means that no application server processing resources are spent on data formatting. By off loading presentation logic to the client, and eliminating the need for frequent page refreshes, Flex applications minimize network traffic and server load.
Common deployment environment Flex applications deploy on a J2EE server and execute on
Flash Player, which is platform-independent, so customers do not need to install custom client software. Also, Flash Player runs consistently in all browsers and platforms, so you do not have to worry about inconsistent behavior in different client environments.

Developing applications for Macromedia Flash Player

The target of a Flex application is Flash Player. Flex developers do not need any Flash authoring background. Rather, a typical Flex developer will have more experience developing applications using a server-based model. Flex lets you use a familiar programming model to develop the client tier and presentation tier.
Flex supports two versions of Flash Player. Flex application users install the standard Flash Player to run Flex applications. Flex also supports the debug version of Flash Player, called Flash Debug Player. Flex application developers use Flash Debug Player during the development process. Flash Debug Player supports important features for developers, including the following:
Error reporting Lets you direct runtime error and warning messages to a log file. Flash Debug
Player can also capture the output of the
trace() function and write it to the log file. For more
information, see Chapter 36, “Debugging Flex Applications,” in Developing Flex Applications.
ActionScript profiling Helps to identify performance bottlenecks in your applications. The
Profiler records the time that Flash Player takes to perform tasks in ActionScript. For more information, see Chapter 37, “Profiling ActionScript,” in Developing Flex Applications.
Debugging support Lets you debug ActionScript files used by your Flex applications. For more
information, see Chapter 36, “Debugging Flex Applications,” in Developing Flex Applications.
10 Chapter 1: Introducing Flex

Flex application characteristics

One of the most common applications using Flex lets users perform product selection and configuration. The user works through a process to configure the features of a product, views or inspects the configuration, and then proceed through the steps required to complete a purchase.
Many types of web applications are appropriate for development in Flex. Some of the requirements of these applications, and how Flex supports these requirements, include the following:
Cross-browser compatibility Web applications should run the same on all browsers and
platforms. By standardizing on Flash Player as the client environment, you are guaranteed a consistent user experience on all platforms and browsers. For more information, see “Developing
applications for Macromedia Flash Player” on page 10.
Client data collecting Collecting user input is one of the most common uses for web
applications. Flex supports forms, and all common form elements, to let you create rich and dynamic user experiences. Flex forms include hooks to the Flex data modeling and data validation mechanism, and the ability to identify required input fields. For more information, see Chapter 6, “Using Layout Containers,” in Developing Flex Applications.
Client-side processing of user input, including filtering and data validation Flex data
management, which includes data models, data validators, data binding, and data services, lets you separate data representation from the way it is viewed by a user. Typically, this design pattern is called Model-View-Controller, or MVC. Flex also provides a powerful way to validate data and pass data between user interface controls and external data sources with little or no server interaction. For more information, see Chapter 31, “Managing Data in Flex,” in Developing Flex Applications.
Multistep processes Many applications present the user with a process that includes a
sequence of steps or decisions that require user input. For example, completing a registration form or checkout form often requires multiple steps to complete.
Ideally, you want your users to be able to navigate through multiple steps on a single page without losing the context of where they are in the process, and without losing any of the previous information that they have already entered. Flex supports the development of these applications by capturing state information, supporting browser Back and Forward buttons using the History Manager, and providing a set of user-interface controls designed explicitly for handling procedural data. For more information, see Chapter 7, “Using Navigator Containers” and Chapter 26, “Using the History Manager,” in Developing Flex Applications.
Information management using master-detail lists A common design pattern for web
applications is to display a list of items, and to let the user explore an item in a detailed way, while leaving the other items unopened. This pattern is referred to as a master-detail list. A master page typically lists database records and corresponding links for each record. When the user clicks a link, a detail page opens that displays more information about the record. Flex supports master/ detail lists through several different controls, including the DataGrid control. For more information, see Chapter 2, “Using Controls,” in Developing Flex Applications.
About Flex 11
Direct user feedback Complex tasks must provide feedback to users when the user makes
input errors or enters invalid information. Support for a feedback mechanism should also require a minimum of server-side interactions so as not to use network bandwidth. Because your applications execute in Flash Player on the client, the Flex feedback mechanism requires little or no server-side logic.

Developing applications

Flex supports a component-based development model. You can use the prebuilt components included with Flex, you can extend the Flex component library by creating new components, or you can combine prebuilt components to create composite components.

Application model

When you build an application using Flex, you describe its user interface using containers and controls. A container is a rectangular region of the screen that contains controls and other containers. Examples of containers are a Form container used for data entry, a Box, and a Grid. A control is a form element, such as a Button or Text Input field.
For example, the following figure shows two different Box containers, each containing three Button controls and a ComboBox control:
Box container with horizontal layout
Box container with vertical layout
This figure shows the controls within a horizontal Box (HBox) container. An HBox container arranges its controls horizontally across the Flash Player drawing surface. The figure also shows the controls in a vertical Box (VBox) container. A VBox container arranges its controls vertically.
Containers and controls define the application’s user interface. In an MVC design pattern, those pieces of the application model represent the view. The model is represented by the data model. Flex data models let you separate your application’s data and business logic from the user interface.
12 Chapter 1: Introducing Flex
You define your data models using MXML or ActionScript as part of a Flex application. The following figure shows a form created in Flex that uses a data model:
Data model
HTTP/SOAP/AMF
Data binding is the process of tying the data in one object to another object. The data model supports bidirectional data binding for writing data from Flex controls to the data model, or for reading data into controls from the model. You can also bind server data to a data model or directly to Flex controls. For example, you can bind the results returned from a web service to the data model, and then have that data propagate to your form controls.
The data model supports automatic data validation. This means that you can use the Flex ZipCode validator to make sure that the value in a model field is a valid ZIP code. If the data is invalid, you can display a message to the user so that the user can correct the error.

How Flex fits the MVC models

The goal of the Model-View-Controller (MVC) architecture is that by creating components with a well-defined and limited scope in your application, you increase the reusability of the components and improve the maintainability of the overall system. Using the MVC architecture, you can partition your system into three categories of components:
Model components Encapsulates data and behaviors related to the data.
View components Defines your application’s user interface.
Server
Controller components Handles the data interconnectivity in your application.
For example, with the MVC design, you could implement a data-entry form that has three distinct pieces:
The model consists of XML data files or the remote data service calls to hold the form data.
The view is the presentation of any data and display of all user interface elements.
The controller holds the user interface logic.
Developing applications 13
Although you can consider a Flex application as part of the View in a distributed MVC architecture, you can use Flex to implement the entire MVC architecture on the client. A Flex application has its own view components that define the user interface, model components to represent data, and controller components responsible for the communication with back-end systems. This client-side separation of task is not available in HTML.

Typical application development steps

You typically develop a Flex application using the following steps:
1.
Within a text editor or integrated development environment (IDE), such as Macromedia Flex Builder, Eclipse, or IntelliJ, insert the MXML root tags into an MXML file.
2.
Add one or more containers.
3.
Add controls to a container, such as input fields, buttons, and output fields.
4.
Define a data model.
5.
Add a web service, HTTP service, or request to a remote Java object.
6.
Add validation to input data.
7.
Add a script to extend a component.

Running Flex applications

Flex application files use the .mxml filename extension. You store these files under the web root directory of your J2EE application.
A request to an MXML file has the following form:
http://hostname/path/filename.mxml
Upon receiving an HTTP request for an MXML file, Flex performs the following steps:
1.
Compiles the MXML file to produce a SWF file.
2.
Caches the compiled SWF file on the server.
3.
Returns the SWF file to the client.
The SWF file executes in Flash Player. While it is executing, the Flex application makes calls to server-side services. For example, the application might issue a SOAP request to a web service, use AMF to connect to a Java object, or make a request to an HTTP service.
Upon subsequent requests to the MXML file, the Flex server determines whether the MXML file has been modified since the previous request. If not, it returns the same SWF file from the cache. If the MXML file has been modified, the Flex server recompiles the file and returns an updated SWF file to the client.
14 Chapter 1: Introducing Flex

The Flex programming model

You deploy the Flex presentation server on a J2EE application server or servlet container. The Flex presentation server includes the Flex application framework and the Flex runtime services, as the following figure shows:
Flex Presentation Server
Flex Application Framework
MXML
Flex Class Library
Flex Runtime Services
ActionScript
J2EE
The Flex application framework consists of the MXML scripting language, the ActionScript programming language, and the Flex class library. You write Flex applications using a combination of MXML and ActionScript. Use MXML to declaratively define the application user interface elements and use ActionScript to define client logic and procedural control.
The Flex class library contains Flex components, managers, and behaviors. With the Flex component-based development model, developers can incorporate prebuilt components, create new components, or combine prebuilt components into composite components.
The Flex runtime services include support for server-side data access, compilation and caching, enterprise resource integration, and deployment runtime needs. All Flex services minimize redundancy and fully exploit existing enterprise resources.

Relationship of the Flex class hierarchy to MXML and ActionScript

Macromedia implemented Flex as an ActionScript class library. That class library contains components (containers and controls), manager classes, data-service classes, and classes for all other features. You develop applications using the MXML and ActionScript languages with the class library.
MXML tags correspond to ActionScript classes or properties of classes. Flex parses MXML tags and compiles a SWF file that contains the corresponding ActionScript objects. For example, Flex provides the ActionScript Button class that defines the Flex Button control. In MXML, you create a Button control using the following MXML statement:
<mx:Button label="Submit" />
The Flex programming model 15
When you declare a control using an MXML tag, you create an instance object of that class. This MXML statement creates a Button object, and initializes the
label property of the Button object
to the string Submit.
An MXML tag that corresponds to an ActionScript class uses the same naming conventions as the ActionScript class. Class names begin with an uppercase letter, and uppercase letters separate the words in class names. Every MXML tag attribute corresponds to a property of the ActionScript object, a style applied to the object, or an event handler for the object. For a complete description of the Flex class library and MXML tag syntax, see the Flex ActionScript and MXML API Reference.

Using MXML and ActionScript

You develop Flex applications using a combination of MXML and ActionScript. MXML is a declarative language that you use to define the basic layout and contents of your application. ActionScript is a procedural language that you use to perform runtime control and data processing in your application.
Defining the user interface in MXML
Your application can consist of one or more MXML files. Using multiple MXML files promotes code reuse, simplifies the process of building a complex application, and makes it easier for more than one developer to contribute to a project.
The following example is an MXML application that uses a Button control to trigger a copy of the text from a TextInput control to a TextArea control:
<?xml version="1.0"?> <!-- ?xml tag must start in line 1 column 1 -->
<!-- MXML root element tag. --> <mx:Application xmlns:mx="http://www.macromedia.com/2003/mxml" >
<!-- Flex controls exist in a container. Define a Panel container. --> <mx:Panel title="My Application">
<!-- TextInput control for user input. --> <mx:TextInput id="myInput" width="150" text="" />
<!-- Button control that triggers the copy. --> <mx:Button id="myButton" label="Copy Text" />
<!-- Output TextArea control. --> <mx:TextArea id="myText" text="" width="150" />
</mx:Panel>
</mx:Application>
The first line of this application specifies the XML declaration and must start in line 1, column 1 of the MXML file.
16 Chapter 1: Introducing Flex
The second line begins with the <mx:Application> tag, the root element of a Flex application. This tag includes the Flex namespace declaration. The content between the beginning and end
<mx:Application> tags defines the Flex application.
As it is written, this example lays out the user interface, but does not yet contain the application logic to copy the input text from the TextInput control to the TextArea control. The next section adds that logic.
Adding ActionScript to a Flex Application
ActionScript follows the ECMA-262 Standard Edition 4 (the specification written by the European Computer Manufacturers Association) unless otherwise noted. For more information on ActionScript, see Chapter 3, “Using ActionScript,” on page 43.
You can use ActionScript for the following purposes:
Handling events The Flex user interface is event-driven. For example, when a user selects a
Button control, the Button generates an event. You handle events by defining functions in ActionScript. Your event handler could open a window, play a SWF file, or perform whatever action is necessary for your application.
Handling errors You handle runtime errors in ActionScript. You can detect data validation
errors and signal the error to the user, resubmit a request to the server, or perform some other actions based on your application.
Binding data objects to a Flex control within an MXML statement You can use data binding
to populate a data model from a Flex control, or populate a control from a data model.
Defining custom components You can derive custom components from the Flex component
class hierarchy to create components specific to your application requirements.
The following example is a modification to the example in the previous section that adds an event handler for the
click event of the Button control. An event handler is ActionScript code that is
executed in response to a user action. The event handler in this example copies the text from the TextInput control to the TextArea control when the user selects the Button control:
<?xml version="1.0"?> <!-- ?xml tag must start in line 1 column 1 -->
<!-- MXML root element tag. --> <mx:Application xmlns:mx="http://www.macromedia.com/2003/mxml" >
<!-- Flex controls exist in a container. Define a Panel container. --> <mx:Panel title="My Application">
<!-- TextInput control for user input. --> <mx:TextInput id="myInput" width="150" text="" />
<!-- Button control that triggers the copy. --> <mx:Button id="myButton" label="Copy Text"
click="myText.text=myInput.text;" />
<!-- Output TextArea control. --> <mx:TextArea id="myText" text="" width="150" />
The Flex programming model 17
</mx:Panel>
</mx:Application>
The previous example inserts the ActionScript code directly into the MXML code. Although this technique works well for one or two lines of ActionScript code, for more complex logic you typically define your ActionScript in an
<?xml version="1.0"?> <!-- ?xml tag must start in line 1 column 1 -->
<mx:Script>
<![CDATA[
function duplicate(){
myText.text=myInput.text;
}
]]>
</mx:Script>
<!-- MXML root element tag --> <mx:Application xmlns:mx="http://www.macromedia.com/2003/mxml" >
<!-- Flex controls exist in a container. Define a Panel container. --> <mx:Panel title="My Application">
<!-- TextInput control for user input. --> <mx:TextInput id="myInput" width="150" text="" />
<!-- Button control that triggers the copy. --> <mx:Button id="myButton" label="Copy Text"
click="duplicate();" />
<mx:Script> block, as the following example shows:
<!-- Output TextArea control. --> <mx:TextArea id="myText" text="" width="150" />
</mx:Panel>
</mx:Application>
In this example, you implement the event handler as an ActionScript function. Flex calls this function in response to the user selecting the Button control. This techniques lets you separate your MXML code from your ActionScript code. You can also choose to divide your application into multiple files to increase its modularity. For more information, see Chapter 3, “Using
ActionScript,” on page 43.
18 Chapter 1: Introducing Flex

Features of Flex

The following table lists details about the Flex feature set. Subsequent chapters in this book describes these features in detail.
Feature Description Details
Containers Defines a region of the
Flash Player drawing surface and controls the layout for everything in the container, including other containers and controls.
Controls Form-based controls
Data modeling Defines the
Data communication services
that handle user interactions and display data that can be directly manipulated by the user.
representation of application data on the client.
Connects to server data using a set of communications services.
Accordion Box Canvas ControlBar DividedBox Form Grid
Alert Button CheckBox ComboBox DataGrid DateChooser DateField HorizontalList HRule HSlider HScrollBar Image Label Link List Loader MediaController MediaDisplay MediaPlayback
Data model for storing application data.
Data binding for unidirectional or bidirectional binding.
to UI controls, and predefined and custom data formatters.
Data validation to validate data model.
Web services for SOAP messages transmitted over
HTTP. Supports both RPC and document operations, and concurrent web service requests.
HTTP service for accessing XML over HTTP and HTTPS.
Remote Java objects let you call methods on local or remote objects (Java objects, JavaBeans, EJBs, JNDI objects) using SOAP or AMF protocols.
Link Bar Panel TabBar TabNavigator Tile TitleWindow ViewStack
Menu MenuBar NumericStepper ProgressBar RadioButton ScrollBars SimpleButton Slider Spacer Text TextArea TextInput TileList ToolTip Tree VRule VSlider VScrollBar
Features of Flex 19
Feature Description Details
Behaviors Enhances the user
Event model Occurrences that require
Style sheets Standard mechanism for
Managers Provides support for
Development tools
Deployment tools
experience through animation, motion, sound, and effects.
a response from a Flex application. User events include a mouse click or a key press. System events include application initialization.
declaring styles.
high-level application tasks.
Used to develop Flex applications.
Used to deploy your Flex applications.
A behavior is a trigger, typically a user action, paired with an effect:
Effects include: Dissolve, Fade, Move, Pause, Resize, WipeDown, WipeLeft, WipeRight, WipeUp.
Triggers include: focusIn, focusOut, hide, move, resize, mouseDown, mouseOver, mouseOut, mouseUp, show.
dragBegin dragComplete dragDrop dragEnter dragExit focusIn focusOut initialize
Used for controlling color, font, sizing, and other attributes of Flex components.
Drag and Drop Manager lets you move data from one place in an application to another.
Cursor Manager lets you control the cursor image within your Flex application.
History Manager lets users navigate through a Flex application using the web browser’s Back and Forward navigation commands.
ToolTipManager displays hints when the user moves the mouse over a Flex control.
Debugger ActionScript Profiler
Player detection Content caching
keyDown keyUpresize mouseDown mouseUp move show
and more
Flex Builder
Deferred instantiation

Where to next

This book contains an introduction to Flex and an overview of developing Flex applications. The Developing Flex Applications book contains detailed information about these topics. For more information, see the following:
For information on MXML and ActionScript, see Chapter 2, “Using MXML,” on page 23,
and Chapter 3, “Using ActionScript,” on page 43.
For information on using Flex components, see Chapter 1, “Using Flex Components,” in
Developing Flex Applications.
For information on developing custom components, see Chapter 15, “Building an Application
with Multiple MXML Files”, and Chapter 18, “Creating ActionScript Components,” in Developing Flex Applications.
20 Chapter 1: Introducing Flex
For more information on the Flex data model, see Chapter 31, “Managing Data in Flex,” in
Developing Flex Applications.
For information on debugging, see Chapter 36, “Debugging Flex Applications,” in Developing
Flex Applications.
Where to next 21
22 Chapter 1: Introducing Flex
CHAPTER 2

Using MXML

MXML is an XML language that you use to lay out user-interface components for Macromedia Flex applications. You also use MXML to declaratively define nonvisual aspects of an application, such as access to server-side data sources and data bindings between user-interface components and server-side data sources. This chapter describes MXML and how you use MXML to develop Flex applications.

Contents

About MXML . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
Basic MXML syntax. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
How MXML relates to standards . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41

About MXML

You use two languages to write Flex applications: MXML and ActionScript. MXML is an XML markup language that you use to lay out user-interface components. You also use MXML to declaratively define nonvisual aspects of an application, such as access to data sources on the server and data bindings between user-interface components and data sources on the server. ActionScript is an object-oriented programming language, based on the ECMAScript Edition 4 proposal, which you use to write programmatic logic for responding to both user-initiated and system-initiated events at runtime.
Like HTML, MXML provides tags that define user interfaces. MXML will seem very familiar if you have worked with HTML. However, MXML is more structured than HTML, and it provides a much richer tag set. For example, MXML includes tags for visual components such as data grids, trees, tab navigators, accordions, and menus, as well as nonvisual components that provide web service connections, data binding, and animation effects. You can also extend MXML with custom components that you reference as MXML tags.
One of the biggest differences between MXML and HTML is that MXML-defined applications are compiled into SWF files and rendered by Macromedia Flash Player, providing a richer and more dynamic user interface than page-based HTML applications do.
MXML does not use concepts specific to Flash, such as the timeline. However, you can use the Flash authoring environment to create or modify components for use in Flex.
23
You can write an MXML application in a single file or in multiple files. MXML supports custom components written in MXML files, ActionScript files, and files created using the Flash MX 2004 authoring environment. Some MXML tags, such as the takes a URL of an external file as a value. For example, you can use the
<mx:Script> tag to reference an external ActionScript file instead of typing ActionScript directly
in the body of the
Note: You specify a script in the source property of an <mx:Script> tag. You do not specify ActionScript classes in the Chapter 18, “Creating ActionScript Components,” in Developing Flex Applications.
<mx:Script> tag.
source property. For information on using ActionScript classes, see
<mx:Script> tag, have a property that
source property in an
MXML supports the following types of URLs:
Absolute; for example:
<mx:Style source="http://www.somesite.com/mystyles.css">
A path used at runtime that is relative to the context root of the Java web application in which
a Flex application is running; for example:
<mx:HTTPService url="@ContextRoot()/directory/myfile.xml"/>
A path used at compile-time that is relative to the context root of the Java web application in
which a Flex application is running; for example:
<mx:Script source="/myscript.as"/>
Relative to the current file location; for example:
<mx:Script source="../myscript.as"/>

Writing a simple application

Because MXML files are ordinary XML files, you have a wide choice of development environments. You can write MXML code in a simple text editor, a dedicated XML editor, or an integrated development environment (IDE) that supports text editing.
Note: MXML filenames must end in a lowercase .mxml file extension.
The following example shows a simple “Hello World” application that contains just an
<mx:Application> tag and one child tag, the <mx:Label> tag. The <mx:Application> tag is
always the root tag of a Flex application. The
<mx:Label> tag represents a Label control, a very
simple user interface component that displays text.
<?xml version="1.0"?> <mx:Application xmlns:mx="http://www.macromedia.com/2003/mxml" >
<mx:Panel title="My Application" marginTop="10" marginBottom="10"
marginLeft="10" marginRight="10" >
<mx:Label text="Hello World!" color="#6601D7" fontSize="24" />
</mx:Panel>
</mx:Application>
24 Chapter 2: Using MXML
The first line of the document specifies an optional declaration of the XML version. It is good practice to include encoding information that specifies how the MXML file is encoded. Many editors let you select from a range of file encoding options. On North American operating systems, ISO-8859-1 is the dominant encoding format, and most programs use that format by default. You can use the UTF-8 encoding format to ensure maximum platform compatibility. UTF-8 provides a unique number for every character in a file, and it is platform-, program-, and language-independent. If you specify an encoding format, it must match the file encoding you use. The following example shows an XML declaration tag that specifies the UTF-8 encoding format:
<?xml version="1.0" encoding="utf-8"?>
To deploy the application, you copy the MXML file to a web application directory. The first time a user requests the MXML file URL in a web browser, the server compiles the MXML code into a SWF file. The server then sends the SWF file to the web browser where it is rendered in Flash Player. Unless the MXML file changes, the SWF file is not recompiled on subsequent requests.
When the Flex compiler autogenerates the HTML file that contains this application, it uses the
height and width properties of the <mx:Application> tag to determine height and width
properties of the
<object> and <embed> tags. The <object> and <embed> tags determine the
size of the Flash drawing surface.
The following figure shows the “Hello World” application rendered in a web browser window:
In addition to being the root tag of a Flex application, the
<mx:Application> tag represents an
Application container. A container is a user-interface component that contains other components and has built-in layout rules for positioning its child components. By default, an Application container lays out its children vertically from top to bottom. You can nest other types of containers inside an Application container to position user-interface components according to other rules. For more information, see Chapter 1, “Using Flex Components,” in Developing Flex Applications.
The properties of an MXML tag, such as the
<mx:Label> tag, let you declaratively configure the initial state of the component. You can use
ActionScript code in an
<mx:Script> tag to change the state of a component at runtime. For
text, color, and fontSize properties of the
more information, see Chapter 16, “Working with ActionScript in Flex,” in Developing Flex Applications.
About MXML 25

Laying out a user interface

MXML provides a comprehensive set of components for laying out the user interface of an application. The standard set of components includes simple form controls, such as buttons and text fields, as well as components for displaying structured data, such as tree controls, list boxes, and combo boxes. MXML also provides container components for layout and navigation. Examples of layout containers include the HBox container for laying out child components horizontally, the VBox container for laying out child components vertically, and the Grid container for laying out child components in rows and columns. Examples of navigator containers include the TabNavigator container for creating tabbed panels, the Accordion navigator container for creating collapsible panels, and the ViewStack navigator container for laying out panels on top of each other.
The following example shows an application that contains a List control on the left side of the user interface and a TabNavigator container on the right side:
<?xml version="1.0"?> <mx:Application xmlns:mx="http://www.macromedia.com/2003/mxml">
<mx:Panel title="My Application" marginTop="10" marginBottom="10"
marginLeft="10" marginRight="10" > <mx:HBox>
<!-- List with three items --> <mx:List>
<mx:dataProvider>
<mx:Array>
<mx:String>Item 1</mx:String> <mx:String>Item 2</mx:String> <mx:String>Item 3</mx:String>
</mx:Array>
</mx:dataProvider>
</mx:List>
<!-- First pane of TabNavigator --> <mx:TabNavigator borderStyle="solid">
<mx:VBox label="Pane1" width="300" height="150" >
<mx:TextArea text="Hello World" /> <mx:Button label="Submit" />
</mx:VBox>
<!-- Second pane of TabNavigator --> <mx:VBox label="Pane2" width="300" height="150" > <!-- Stock view goes here --> </mx:VBox>
</mx:TabNavigator>
</mx:HBox>
</mx:Panel>
</mx:Application>
26 Chapter 2: Using MXML
The List control and TabNavigator container are laid out side by side because they are in an HBox container. The controls in the TabNavigator container are laid out from top to bottom because they are in a VBox container.
The following figure shows the application rendered in a web browser window:
For more information about laying out user-interface components, see Chapter 1, “Using Flex Components,” in Developing Flex Applications.

Using MXML to trigger runtime code

Flex applications are driven by runtime events. You can specify event handlers, which consist of code for handling runtime events, in the event properties of MXML tags. For example, the
<mx:Button> tag has a click event property in which you can specify ActionScript code that
executes when the Button control is clicked at runtime. You can specify simple event handler code directly in event properties. To use more complex code, you can specify the name of an ActionScript function defined in an
<mx:Script> tag.
The following example shows an application that contains a Button control and a TextArea control. The value of the TextArea control’s
<?xml version="1.0"?> <mx:Application xmlns:mx="http://www.macromedia.com/2003/mxml">
click property of the Button control contains a simple event handler that sets the
text property to the text Hello World.
<mx:Panel title="My Application" marginTop="10" marginBottom="10"
marginLeft="10" marginRight="10" >
<mx:TextArea id="textarea1"/> <mx:Button label="Submit" click="textarea1.text='Hello World';"/>
</mx:Panel>
</mx:Application>
The following figure shows the application rendered in a web browser window:
About MXML 27
The following example shows the code for a version of the application in which the event handler is contained in an ActionScript function in an
<?xml version="1.0"?> <mx:Application xmlns:mx="http://www.macromedia.com/2003/mxml">
<mx:Script>
<![CDATA[
function hello(){
textarea1.text="Hello World";
}
]]>
</mx:Script>
<mx:Panel title="My Application" marginTop="10" marginBottom="10"
marginLeft="10" marginRight="10" >
<mx:TextArea id="textarea1"/> <mx:Button label="Submit" click="hello();"/>
</mx:Panel>
</mx:Application>
<mx:Script> tag:
For more information about using ActionScript with MXML, see Chapter 16, “Working with ActionScript in Flex,” in Developing Flex Applications.

Binding data between components

Flex provides simple syntax for binding the properties of components to each other. In the following example, the value inside the curly braces ({ }) binds the
text property of a TextArea
control to the text property of a TextInput control. When the application initializes, both controls display the text Hello. When the user clicks the Button control, both controls display the text Goodbye.
<?xml version="1.0"?> <mx:Application xmlns:mx="http://www.macromedia.com/2003/mxml">
<mx:Panel title="My Application" marginTop="10" marginBottom="10"
marginLeft="10" marginRight="10" >
<mx:TextInput id="textinput1" text="Hello"/> <mx:TextArea id="textarea1" text="{textinput1.text}"/> <mx:Button label="Submit" click="textinput1.text='Goodbye';"/>
</mx:Panel> </mx:Application>
28 Chapter 2: Using MXML
The following figure shows the application rendered in a web browser window after the user clicks the Submit button:
As an alternative to the curly braces ({ }) syntax, you can use the
<mx:Binding> tag, in which you
specify the source and destination of a binding. For more information about data binding, see Chapter 32, “Binding and Storing Data in Flex,” in Developing Flex Applications.

Using data services

Flex is designed to interact with several types of services that provide access to local and remote server-side logic. For example, a Flex application can connect to a web service that uses the Simple Object Access Protocol (SOAP), a Java object residing on the same application server as Flex using AMF, or an HTTP URL that returns XML. AMF is the protocol used in Flash Remoting MX. The MXML components that provide data access are called data service components. MXML includes the following types of data service components:
WebService provides access to SOAP-based web services
HTTPService provides access to HTTP URLs that return data
RemoteObject provides access to Java objects using the AMF protocol
The following example shows an application that calls a web service that provides weather information, and displays the current temperature for a given ZIP code. The application binds the ZIP code that a user enters in a TextInput control to a web service input parameter. It binds the current temperature value contained in the web service result to a TextArea control.
<?xml version="1.0"?> <mx:Application xmlns:mx="http://www.macromedia.com/2003/mxml" >
<!-- Define the web service connection
(the specified WSDL URL is not functional). -->
<mx:WebService id="WeatherService"wsdl="/ws/WeatherService?wsdl">
<!-- Bind the value of the ZIP code entered in the TextInput control
to the ZipCode parameter of the GetWeather operation. -->
<mx:operation name="GetWeather">
<mx:request>
<ZipCode>{zip.text}</ZipCode>
</mx:request>
</mx:operation>
</mx:WebService> <mx:Panel title="My Application" marginTop="10" marginBottom="10"
marginLeft="10" marginRight="10" >
About MXML 29
<!-- Provide a ZIP code in a TextInput control. -->
<mx:TextInput id="zip" width="200" text="Zipcode please?"/>
<!-- Call the web service operation with a Button click. -->
<mx:Button width="60" label="Get Weather"
click='WeatherService.GetWeather.send()'/>
<!-- Display the location for the specified ZIP code. -->
<mx:Label text="Location:"/> <mx:TextArea text="{WeatherService.GetWeather.result.Location}"/>
<!-- Display the current temperature for the specified ZIP code. -->
<mx:Label text="Temperature:"/> <mx:TextArea text="{WeatherService.GetWeather.result.CurrentTemp}"/>
</mx:Panel>
</mx:Application>
The following figure shows the application rendered in a web browser window:
For more information about using data services, see Chapter 31, “Managing Data in Flex,” in Developing Flex Applications.

Storing and validating application-specific data

You can use a data model to store application-specific data. A data model is an ActionScript object that provides properties for storing data, and optionally contains methods for additional functionality. You can declare a simple data model that does not require methods in an
<mx:Model> tag or <mx:XML> tag. You can use validator components to validate data stored in a
data model. Flex includes a set of standard validator components. You can also create your own.
The following example shows an application that contains TextInput controls for entering personal contact information; a data model, represented by the
<mx:Model> tag, for storing the
contact information; and validator components for validating that the expected type of data is entered in the TextInput fields. Validation is triggered automatically when data binding occurs. If validation fails, the user receives immediate visual feedback.
<?xml version="1.0"?> <mx:Application xmlns:mx="http://www.macromedia.com/2003/mxml" >
<mx:Panel title="My Application" marginTop="10" marginBottom="10"
marginLeft="10" marginRight="10" >
30 Chapter 2: Using MXML
<!-- The user enters contact information in TextInput controls. -->
<mx:TextInput id="homePhoneInput"
text="This isn't a valid phone number."/> <mx:TextInput id="cellPhoneInput" text="(999)999-999"/> <mx:TextInput id="emailInput" text="me@somewhere.net"/>
</mx:Panel>
<!-- A data model called "contact" stores contact information.
The text property of each TextInput control shown above is passed to a field of the data model. -->
<mx:Model id="contact"> <homePhone>{homePhoneInput.text}</homePhone> <cellPhone>{cellPhoneInput.text}</cellPhone> <email>{emailInput.text}</email>
</mx:Model>
<!-- Validator components validate data stored in the
fields of the contact data model. -->
<mx:PhoneNumberValidator field="contact.homePhone"/>
<mx:PhoneNumberValidator field="contact.cellPhone"/>
<mx:EmailValidator field="contact.email"/>
</mx:Application>
The following figure shows the application rendered in a web browser window:
For more information about using data models, see Chapter 31, “Managing Data in Flex,” in Developing Flex Applications.

Formatting application-specific data

Formatter components are ActionScript components that perform a one-way conversion of raw data to a formatted string. They are triggered just before data is displayed in a text field. Flex includes a set of standard formatters. You can also create your own formatters. The following example shows an application that uses the standard ZipCodeFormatter component to format the value of a variable:
<?xml version="1.0"?> <mx:Application xmlns:mx="http://www.macromedia.com/2003/mxml">
<!-- Declare a ZipCodeFormatter and define parameters. -->
<mx:ZipCodeFormatter id="ZipCodeDisplay" formatString="#####-####" />
<mx:Script>
<![CDATA[
var storedZipCode=123456789;
About MXML 31
]]> </mx:Script> <mx:Panel title="My Application" marginTop="10" marginBottom="10"
marginLeft="10" marginRight="10" >
<!-- Trigger the formatter while populating a string with data. -->
<mx:TextInput text="{ZipCodeDisplay.format(storedZipCode)}" />
</mx:Panel>
</mx:Application>
The following figure shows the application rendered in a web browser window:
For more information about formatter components, see Chapter 34, “Formatting Data,” in Developing Flex Applications.

Using Cascading Style Sheets (CSS)

You can use style sheets based on the Cascading Style Sheets (CSS) standard to declare styles to Flex components. The
<mx:Style> tag contains inline style definitions or a reference to an
external file that contains style definitions.
The
<mx:Style> tag must be an immediate child of the root tag of the MXML file. You can
apply styles to an individual component using a class selector, or to all components of a certain type using a type selector.
The following example defines a class selector and a type selector in the class selector and the type selector are applied to the Button control:
<?xml version="1.0"?> <mx:Application xmlns:mx="http://www.macromedia.com/2003/mxml">
<mx:Style>
.myclass { color: Red } /* class selector */
Button { font-size: 18pt} /* type selector */ </mx:Style>
<mx:Panel title="My Application" marginTop="10" marginBottom="10"
marginLeft="10" marginRight="10" >
<mx:Button styleName="myclass" label="This is red 18 point text."/>
</mx:Panel>
</mx:Application>
32 Chapter 2: Using MXML
<mx:Style> tag. Both the
The following figure shows the application rendered in a web browser window:
For more information about using Cascading Style Sheets, see Chapter 20, “Using Styles and Fonts,” in Developing Flex Applications.

Using effects

An effect is a change to a component that occurs over a brief period of time. Examples of effects are fading, resizing, and moving a component. An effect is combined with a trigger, such as a mouse click on a component, a component getting focus, or a component becoming visible, to form a behavior. In MXML, you apply effects as properties of a control or container. Flex provides a set of built-in effects with default properties.
The following example shows an application that contains a Button control with its
mouseOverEffect property set to the standard Zoom effect. The Zoom effect executes when the
user moves the mouse pointer over the Button control.
<?xml version="1.0"?> <mx:Application xmlns:mx="http://www.macromedia.com/2003/mxml">
<mx:Panel title="My Application" marginTop="10" marginBottom="10"
marginLeft="10" marginRight="10" >
<mx:Button id="myButton" mouseOverEffect="Zoom" />
</mx:Panel>
</mx:Application>
You can use the <mx:Effect> tag to customize a standard effect or combine effects into a composite effect. For more information about effects, see Chapter 21, “Using Behaviors,” in Developing Flex Applications.

Using MXML components

MXML components are MXML files that you use as custom tags in other MXML files. They encapsulate and extend the functionality of existing Flex components. Just like MXML application files, MXML component files can contain a mix of MXML tags and ActionScript code. The name of the MXML file becomes the class name with which you refer to the component in another MXML file.
Note: You cannot access MXML component URLs directly in a web browser.
The following example shows a custom ComboBox control that is prepopulated with list items:
<?xml version="1.0"?> <!-- MyComboBox.mxml -->
<mx:VBox xmlns:mx="http://www.macromedia.com/2003/mxml">
<mx:ComboBox >
About MXML 33
<mx:dataProvider>
<mx:Array> <mx:String>Dogs</mx:String> <mx:String>Cats</mx:String>
</mx:Array>
</mx:ComboBox>
</mx:VBox>
<mx:String>Mice</mx:String>
</mx:dataProvider>
The following example shows an application that uses the MyComboBox component as a custom tag. The value * assigns the local namespace to the current directory.
<?xml version="1.0"?> <!-- MyApplication.mxml --> <mx:Application xmlns:mx="http://www.macromedia.com/2003/mxml"
xmlns:local="*"> <mx:Panel title="My Application" marginTop="10" marginBottom="10"
marginLeft="10" marginRight="10" >
<local:MyComboBox/>
</mx:Panel>
</mx:Application>
The following figure shows the application rendered in a web browser window:
For more information about MXML components, see Chapter 15, “Building an Application with Multiple MXML Files,” in Developing Flex Applications.
You can also define custom Flex components in ActionScript and the Flash MX 2004 authoring tool. For more information, see Chapter 3, “Using ActionScript.”

Using XML namespaces

In an XML document, tags are associated with a namespace. XML namespaces let you refer to more than one set of XML tags in the same XML document. The
xmlns property in an MXML
tag specifies an XML namespace. To use the default namespace, specify no prefix. To use additional tags, specify a tag prefix and a namespace. For example, the following
<mx:Application> tag indicates that tags in the MXML namespace use the prefix mx:.
xmlns property in the
The Universal Resource Identifier (URI) for the MXML namespace is http://www.macromedia.com/2003/mxml.
<mx:Application xmlns:mx="http://www.macromedia.com/2003/mxml" >
34 Chapter 2: Using MXML
XML namespaces give you the ability to use custom tags that are not in the MXML namespace. The following example shows an application that contains a custom tag called CustomBox. The namespace value
containers.boxes.* indicates that an MXML component called CustomBox
is in the containers/boxes directory.
<?xml version="1.0"?> <mx:Application xmlns:mx="http://www.macromedia.com/2003/mxml"
xmlns:my="containers.boxes.*"> <mx:Panel title="My Application" marginTop="10" marginBottom="10"
marginLeft="10" marginRight="10" >
<my:CustomBox/>
</mx:Panel>
</mx:Application>
The containers/boxes directory can be a subdirectory of the directory containing the application file, or it can be a subdirectory of one of the ActionScript classpath directories assigned in the flex-config.xml file. If copies of the same file exist in both places, Flex uses the file in the application file directory. The prefix name is arbitrary, but it must be used as declared.
When using a component contained in a SWC file, the package name and the namespace must match, even though the SWC file is in the same directory as the MXML file that uses it. For more information about SWC components, see Developing Flex Applications.

Basic MXML syntax

Most MXML tags correspond to ActionScript 2.0 classes or properties of classes. Flex parses MXML tags and compiles a SWF file that contains the corresponding ActionScript objects.
ActionScript 2.0 is a new version of ActionScript that uses syntax based on the ECMAScript Edition 4 proposal. ActionScript 2.0 includes the following features:
Formal class definition syntax
Formal packages structure
Typing of variables, parameters, and return values (compile-time only)
Implicit getters and setters that use the get and set keywords
Inheritance
Public and private members
Static members
Cast operator
For more information about ActionScript 2.0, see Chapter 3, “Using ActionScript,” on page 43.
Basic MXML syntax 35

Naming MXML files

MXML filenames must adhere to the following naming conventions:
Filenames must be valid ActionScript identifiers, which means they must start with a letter or
underscore character (_), and they can only contain letters and numbers and underscore characters after that.
Filenames must not be the same as ActionScript class names, component id values, or the
word application. Do not use filenames that match the names of MXML tags that are in the mx namespace.
Filenames must end with a lowercase .mxml file extension.

Using tags that represent ActionScript classes

An MXML tag that corresponds to an ActionScript class uses the same naming conventions as the ActionScript class. Class names begin with a capital letter, and capital letters separate the words in class names. For example, when a tag corresponds to an ActionScript class, its properties correspond to the properties and events of that class.

Setting component properties

In MXML, a component property uses the same naming conventions as the corresponding ActionScript class. A property names begins with a lower case letter, and capital letters separate words in the property names. You can set the values of properties using tag attributes or child tags. Macromedia recommends that you assign scalar values and simple binding expressions as attributes and that you assign complex types as child tags. Each of a component’s properties is one of the following types:
Scalar properties, such as a number or string
Array of scalar values, such as an array of numbers or strings
ActionScript object
Array of ActionScript objects
ActionScript properties
XML data
Style properties
Scalar properties
You usually specify the value of a scalar property as a property of a component tag, as the following example shows:
<Label width="50" height="25" text="Hello World"/>
Note: A tag property cannot consist of the @ character followed by one or more characters.
36 Chapter 2: Using MXML
Arrays of scalar values
When a class has a property that takes an Array as its value, you can represent the property in MXML using child tags. The component in the following example has a
dataProvider property
that contains an Array of numbers:
<mx:List>
<mx:dataProvider>
<mx:Array>
<mx:Number>94062</mx:Number> <mx:Number>14850</mx:Number> <mx:Number>53402</mx:Number>
</mx:Array> </mx:dataProvider>
</mx:List>
Objects
When a component has a property that takes an object as its value, you can represent the property in MXML using child tags, as the following example shows:
<mynamespace:MyComponent>
<mynamespace:nameOfProperty>
<objectType prop1="val1" prop2="val2"/> </mynamespace:nameOfProperty>
</mynamespace:MyComponent>
The following example shows an ActionScript class that defines an Address object. This object is used as a property of the PurchaseOrder component in the next example.
class example.Address { var name : String; var street : String; var city: String; var state: String; var zip: Number; }
The following example shows an ActionScript class that defines a PurchaseOrder component that has a property type of Address:
import example.Address;
class example.PurchaseOrder { public var shippingAddress : Address; public var quantity : Number; ... }
In MXML, you define the PurchaseOrder component as the following example shows:
<e:PurchaseOrder quantity="3" xmlns:e="example"> <e:shippingAddress> <e:Address name="Fred" street="123 Elm St."/> </e:shippingAddress> </e:PurchaseOrder>
Basic MXML syntax 37
If the value of the shippingAddress property is a subclass of Address (such as DomesticAddress), you can declare the property value as the following example shows:
<e:PurchaseOrder quantity="3" xmlns:e="example">
<e:shippingAddress>
<e:DomesticAddress name="Fred" street="123 Elm St."/> </e:shippingAddress>
</e:PurchaseOrder>
If the property is explicitly typed as Object like the value property in the following example, you can specify an anonymous object using the
class ObjectHolder { var value : Object }
<mx:Object> tag.
The following example shows how you specify an anonymous object as the value of the value property:
<mynamespace:ObjectHolder>
<mynamespace:value>
<mx:Object foo='bar' /> </mynamespace:value>
</mynamespace:ObjectHolder>
Arrays of objects
When a component has a property that takes an Array of objects as its value, you can represent the property in MXML using child tags, as the following example shows:
<mynamespace:MyComponent>
<mynamespace:nameOfProperty>
<mx:Array>
<objectType prop1="val1" prop2="val2"/> <objectType prop1="val1" prop2="val2"/> <objectType prop1="val1" prop2="val2"/>
</mx:Array> </mynamespace:nameOfProperty>
</mynamespace:MyComponent>
The component in the following example contains an Array of ListItem objects. Each ListItem object has properties named
<mynamespace:MyComponent>
<mynamespace:dataProvider>
<mx:Array>
<mynamespace:ListItem label="One" data="1"/> <mynamespace:ListItem label="Two" data="2"/>
</mx:Array> </mynamespace:dataProvider>
</mynamespace:MyComponent>
label and data.
38 Chapter 2: Using MXML
The following example shows how you specify an anonymous object as the value of the
dataProvider property:
<mynamespace:MyComponent>
<mynamespace:dataProvider>
<mx:Array>
<mx:Object label="One" data="1" /> <mx:Object label="Two" data="2" />
</mx:Array> </mynamespace:dataProvider>
</mynamespace:MyComponent>
Properties that contain XML data
If a component contains a property that takes XML data, the value of the property is an XML fragment to which you can apply a namespace. In the following example, the
value property of
the MyComponent object is XML data:
<mynamespace:MyComponent>
<mynamespace:value xmlns:a="http://www.example.com/myschema">
<mx:XML>
<a:purchaseorder>
<a:billingaddress> ... </a:billingaddress> ...
</a:purchaseorder> </mx:XML>
</mynamespace:value> </mynamespace:MyComponent>
Style properties
A style property of an MXML tag differs from other properties because it corresponds to an ActionScript style property that you set in ActionScript using the
method rather than object.property=value notation. The text and fontFamily
value)
setStyle(stylename,
properties in the following example:
<mx:TextArea id="myText" text="hello world" fontFamily="Tahoma"/>
are equivalent to the following ActionScript code:
// text property: myText.text= "hello world";
// font style property:
myText.setStyle("fontFamily", "Tahoma");
Basic MXML syntax 39

Compiler tags

Compiler tags are tags that do not directly correspond to ActionScript objects or properties. The names of the following compiler tags have just the first letter capitalized:
<mx:Binding>
<mx:Effect>
<mx:Model>
<mx:Script>
<mx:Style>
<mx:Metadata>
The following compiler tags are in all lowercase letters:
<mx:operation>
<mx:request>
<mx:method>
<mx:arguments>

Identifier properties on MXML tags

With a few exceptions (see “MXML tag syntax” on page 41), a tag that corresponds to a component has an optional has an
id property, you can reference the corresponding object in ActionScript.
In the following example, results from a web service request are traced in the function:
<?xml version="1.0"?> <mx:Application xmlns:mx="http://www.macromedia.com/2003/mxml"> ...
id property, which must be unique within the MXML file. If a tag
writeToLog
<mx:VBox>
<mx:TextInput id="myText" text="Hello World!" />
<mx:Button id="mybutton" label="Get Weather" click="writeToLog();"/> </mx:VBox> <mx:Script>
<![CDATA[
function writeToLog() {
trace(myText.text);
}
]]> </mx:Script>
</mx:Application>
Because each id value in an MXML file is unique, all objects in a file are part of the same flat namespace. You do not qualify an object by referencing its parent with dot notation, as in
myVBox.myText.text.
40 Chapter 2: Using MXML

MXML tag syntax

MXML has the following syntax requirements:
The id property is not required on any tag.
The id property is not allowed on the root tag.
Boolean properties only take true and false values.
The <mx:Binding> tag requires both source and destination properties.
The <mx:Binding> tag cannot contain an id property.
The <mx:Validator> tag and its subclasses require a field property.
The <mx:Validator> tag cannot contain an id property.
The <mx:WebService> tag requires either a wsdl value or serviceName value, and does not
allow both.
The <mx:RemoteObject> tag requires either a source value or a named value, and does not
allow both.
The <mx:HTTPService> tag requires either a url value or a serviceName value, and does not
allow both.
The <mx:operation> tag requires a name value, and does not allow duplicate name entries.
The <mx:operation> tag cannot contain an id property.
The <mx:method> tag requires a name value and does not allow duplicate name entries.
The <mx:method> tag cannot contain an id property.

How MXML relates to standards

MXML uses standards extensively. This section describes how MXML relates to standards for the following:
XML
Event models
Web services
Java
HTTP
Graphics
Cascading Style Sheets

XML standards

You write Flex applications in XML documents. XML documents use tags to define pieces of structured information and the relationships between them. In MXML, the tag defines the root of an application. You define the parts of the application in child tags of the
<mx:Application> tag. Examples of MXML tags include container tags, such as <mx:VBox>,
which define rectangular regions of the user interface, and control tags, such as which define typical user interface controls.
How MXML relates to standards 41
<mx:Application>
<mx:TextInput>,

Event model standards

The Flex event model is a subset of Document Object Model (DOM) Level 3 Events, a World Wide Web Consortium (W3C) working draft. DOM Level 3 defines an event system that allows platform- and language-neutral registration of event handlers, describes event flow through a tree structure, and provides basic contextual information for each event. MXML provides tag properties that let you specify ActionScript code to handle events. For example, the
click event
handler specified in the following example sends a web service request:
<mx:Button click="mywebservice.myOperation.send()”/>

Web services standards

Flex provides MXML tags for interacting with web services that define their interfaces in a Web Services Description Language (WSDL) document available as a URL. WSDL is a standard format for describing the messages that a web service understands, the format of its responses to those messages, the protocols that the web service supports, and where to send messages.
Flex applications support web service requests and results that are formatted as Simple Object Access Protocol (SOAP) messages and are transported using the Hypertext Transfer Protocol (HTTP). SOAP provides the definition of the XML-based format that you can use for exchanging structured and typed information between a web service client, such as a Flex application, and a web service.

Java standards

Flex provides MXML tags for interacting with server-side Java objects, including plain old Java objects (POJOs), JavaBeans, and Enterprise JavaBeans (EJBs).

HTTP standards

Flex provides MXML tags for making standard HTTP GET and POST requests, and working with data returned in HTTP responses.

Graphics standards

Flex provides MXML tags for using JPEG, GIF, and PNG images in an application. Flex also provides tags for importing Macromedia SWF files and Scalable Vector Graphics (SVG) files into an application.

Cascading Style Sheets standards

MXML styles are defined and used according to the W3C Cascading Style Sheets (CSS) standard. CSS provides a mechanism for declaring text styles and visual effects that you can apply to Flex components.
42 Chapter 2: Using MXML
CHAPTER 3

Using ActionScript

Macromedia Flex developers can use ActionScript to extend the functionality of their Flex applications. ActionScript provides flow control and object manipulation features that are not available in strict MXML. This chapter introduces ActionScript and explains how to use ActionScript in an MXML application.
For more information on ActionScript, see Flex ActionScript Language Reference.

Contents

About ActionScript . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43
Using ActionScript in Flex applications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46
Creating ActionScript components . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53
Techniques for separating ActionScript from MXML. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54

About ActionScript

ActionScript is the programming language for Macromedia Flash Player. ActionScript includes built-in objects and functions, and lets you create your own objects and functions.
Note: The ActionScript programming language in Flash MX 2004 and Flex follows the ECMA 4 standard proposed by the Mozilla project.
ActionScript is similar to the core JavaScript programming language. You don’t need to know JavaScript to use ActionScript; however, if you know JavaScript, ActionScript will appear familiar to you. The following are some of the many resources available that provide more information about general programming concepts and the JavaScript language:
The European Computers Manufacturers Association (ECMA) document ECMA-262 is
derived from JavaScript and serves as the international standard for the JavaScript language.
ActionScript is based on the ECMA-262 specification, which is available from www.ecma-
international.org. ECMA-262 is also known as ECMAScript. ActionScript is primarily based
on Edition 3 of this standard, which is also referred to commonly as ECMA 3 (shorthand for ECMA-262 Edition 3).
43
Netscape DevEdge Online has a JavaScript Developer Central site
(http://developer.netscape.com/tech/javascript/index.html) that contains documentation and articles about ActionScript.
Core JavaScript Guide.
For more information about using ActionScript in Flex, see Flex ActionScript Language Reference, which is included in the Flex documentation set.

Comparing ActionScript and ECMAScript (JavaScript)

The following are some of the differences between ActionScript and JavaScript:
ActionScript does not support browser-specific objects such as Document, Window,
and Anchor.
ActionScript does not completely support all of the JavaScript built-in objects.
ActionScript supports syntax constructs that are not permitted in JavaScript (for example, the
tellTarget and ifFrameLoaded actions and slash syntax) to support previous releases.
However, Macromedia does not recommend the use of these syntax constructs; instead, use ActionScript elements that are like those in JavaScript (for example, and dot syntax).
with, _framesloaded,
ActionScript does not support some JavaScript syntax constructs, such as statement labels.
In ActionScript, the eval action can only perform variable references.
In JavaScript, when a string is evaluated in a Boolean context and the string has a nonzero
length, the result is ActionScript, the string is converted to a number. If the number is nonzero, the result is otherwise, the result is
true; if the string doesn’t have a nonzero length, the result is false. In
false.
true;

About ActionScript in MXML applications

ActionScript extends the capabilities of Flex application developers. With ActionScript, you can define event listeners and handlers, get or set component properties, handle callback functions, and create new classes, packages, and components.
You can use ActionScript in your Flex applications in the following ways:
Insert ActionScript code blocks with the <mx:Script> tag. In these code blocks, you can add
new functions, handle errors and events, and perform other tasks in your application or its supporting MXML files.
Call global ActionScript functions that are stored in the system_classes directory structure.
Reference external classes and packages in user_classes to handle more complex tasks. This lets
you take advantage of ActionScript support for object-oriented programming concepts such as code reuse and inheritance.
Use standard Flex components. The logic of components and helper classes in the Flex
application model is based on ActionScript classes.
Extend existing components with ActionScript classes.
44 Chapter 3: Using ActionScript
Create new components in ActionScript.
Create new components in the Flash authoring environment (SWC files).
Flex ActionScript packages
Flex includes a standard set of ActionScript classes and packages that define the Flex components and provide helper classes. These packages are in the Flex application WAR file under flex_app_root/WEB-INF/flex/system_classes. These packages are available to all Flex applications and do not require explicit import statements.
In addition, Flex includes a SWC file in the flex_app_root/WEB-INF/flex/frameworks directory that provides all the necessary symbols for Flex components. A debug version of this SWC file is located in the flex_app_root/WEB-INF/flex/frameworks_debug directory.
ActionScript compilation
The logic of your Flex application can consist of ActionScript classes, MXML files, SWF files, and external components in the form of SWC components, MXML files, or ActionScript files. The end result of all the input files is a SWF file that is downloaded by Flash Player and played on the client’s machine.
You can use ActionScript in code fragments within your MXML files. The Flex compiler transforms the main MXML file and its child files into a single ActionScript class. As a result, you cannot define classes or use statements outside of functions in MXML files and included ActionScript files.
You can reference imported ActionScript classes from your MXML application files, and those classes are added to the final SWF file.
When the transformation to an ActionScript file is complete, Flex links all the ActionScript components and includes those classes in the final SWF file.
About ActionScript 45
The following figure shows the source files used to generate a SWF file that your J2EE server
S
Fil
sends to the client:
ource
The top-level MXML file includes <mx:script> blocks, imported ActionScript files, and components defined by ActionScript files or MXML files.
ActionScript classes and packages referenced in the application files are included in the final SWF.
es
Compiler/Linker
J2EE Server
Client

Using ActionScript in Flex applications

When you write a Flex application, you use MXML to lay out the user interface of your application, and you use ActionScript to handle the user interactions with the application. You can use a variety of methods to mix ActionScript and MXML. You can include inline ActionScript in MXML, or supplement a codeless MXML document with an external ActionScript controller class.
To use ActionScript in your Flex applications, you can add script blocks using the tag or include external ActionScript files. In addition, you can import external class files or entire packages of class files for use by your MXML application. Flex extracts the ActionScript and creates a class file, which is linked to the final SWF file. For more information, see “Techniques
for separating ActionScript from MXML” on page 54.
Note: In general, Macromedia recommends that you import ActionScript class files when possible rather than use multiple files.
<mx:Script> blocks in your MXML files or include snippets of ActionScript code from
<mx:Script>

Using special characters

Special characters are any characters that might confuse the XML parser. The contents of
<mx:Script> tags are treated as XML by Flex. As a result, blocks of ActionScript should be
wrapped in a CDATA construct so that Flex does not try to interpret special characters. The following example shows a CDATA construct:
<![CDATA[
...
]]>
46 Chapter 3: Using ActionScript
Flex does not parse text in a CDATA construct so that you can use XML-parsed characters such as angle brackets (< and >) and ampersand (&). For example, the following script that includes a less than (<) comparison must be in a CDATA construct:
<mx:Script>
<![CDATA[ function changeText() {
var x:Number = 1;
if (x<3) {
ta1.text = "Hello world";
} } ]]>
</mx:Script>

Referring to Flex components

When you refer to Flex components in ActionScript, the component must have an set. You then use the
id to refer to that component.
id property
For example, you can define a TextArea control in MXML using the
<mx:TextArea> tag, as the
following example shows.
<?xml version="1.0"?> <mx:Application xmlns:mx="http://www.macromedia.com/2003/mxml" >
<mx:TextArea id="ta1" text="Congratulations. You are a winner." />
</mx:Application>
To access that component’s methods or properties, use dot syntax. The following example gets the value of the TextArea named ta1:
var str:String = ta1.text;
You can refer to the current enclosing document or current object using the this keyword. For more information, see Chapter 16, “Working with ActionScript in Flex,” in Developing Flex Applications.

Using ActionScript blocks in MXML files

ActionScript blocks can contain ActionScript functions and variable declarations when used in MXML applications.
Statements and expressions are only allowed if they are wrapped in a function. In addition, you cannot define new classes or interfaces in
<mx:Script> blocks. All ActionScript in the blocks is
added to the enclosing file’s class when Flex compiles the application.
When using an
<mx:Script> block, you must wrap the contents in a CDATA construct. This
prevents the compiler from interpreting the contents of the script block as XML, and allows the ActionScript to be properly generated. As a result, Macromedia recommends that you write all your
<mx:Script> open and close tags as the following example shows:
<mx:Script>
<![CDATA[
... ]]>
</mx:Script>
Using ActionScript in Flex applications 47
The script within a given <mx:Script> tag is accessible from any component in the MXML file. The
<mx:Script> tag must be located at the top level of the MXML file (within the Application
tag or other top-level component tag). You can define multiple script blocks in your MXML files, but you should try to keep them in one location to improve readability.
The following example declares a variable and a function:
<?xml version="1.0"?> <mx:Application xmlns:mx="http://www.macromedia.com/2003/mxml">
<mx:Script>
<![CDATA[
var z:Number;
function doSomething() {
z = z + 1; // This must be in a function.
} ]]>
</mx:Script> ... </mx:Application>

Including ActionScript code versus importing ActionScript classes

To make your MXML code more readable, you can also reference ActionScript files in your
<mx:Script> tags, rather than insert large blocks of script. You can include or import
ActionScript files.
There is a distinct difference between including and importing in ActionScript. Including is copying lines of code from one file into another. Importing is adding a reference to a class file or package so that you can access objects and properties defined by external classes. Files that you import must be found in the ActionScript classpath. Files that you include must be located relative to the application root or use an absolute path.
You use the
#include directive or the <mx:Script source="filename"> tag to add
ActionScript code snippets to your Flex applications.
You use
import statements in an <mx:Script> block to add ActionScript classes and packages to
your Flex applications.
Including ActionScript files
Flex lets you point to external ActionScript files in your
<mx:Script> tags. At compile-time, the
compiler copies the entire contents of the file into your MXML application. As with ActionScript in an
<mx:Script> block, ActionScript in included files must be variable declarations or in
functions. You cannot define classes in included files.
Variables and functions defined in an included ActionScript file are available to any component in the MXML file. An included ActionScript file is not the same as an imported ActionScript class. Flex provides access to the included file’s variables and functions, but does not add a new class, since the MXML file itself is a class.
48 Chapter 3: Using ActionScript
Included ActionScript files do not need to be in the same directory as the MXML file. However, you should organize your ActionScript files in a logical directory structure.
Flex detects changes in ActionScript files using timestamps. If the file has changed since the last request, Flex regenerates the application before responding to the client. If you change the ActionScript in one of the imported ActionScript files, the next time the application is requested, the changes appear.
There are two ways to include an external ActionScript file in your Flex application:
The source attribute of the <mx:Script> tag. This is the preferred method for including
external ActionScript class files.
The #include directive inside <mx:Script> blocks.
The following sections describe these two methods of including an external ActionScript file.
Using the source attribute
You use the your Flex applications. This provides a way to make your MXML files less cluttered and promotes code reuse across different applications.
The following example shows the contents of the IncludedFile.as file:
public function computeSum(a:Number, b:Number):Number {
return a + b;
}
The following example imports the contents of the IncludedFile.as file. This file is located in the same directory as the MXML file.
<?xml version="1.0"?> <mx:Application xmlns:mx="http://www.macromedia.com/2003/mxml">
source attribute of the <mx:Script> tag to include external ActionScript files in
<mx:Script source="IncludedFile.as" />
<mx:TextInput id="ta1st" text="3"/>
<mx:TextInput id="ta2nd" text="3"/>
<mx:TextArea id="taMain"/>
<mx:Button id="b1" label="Compute Sum"
click="taMain.text=computeSum(Number(ta1st.text), Number(ta2nd.text))"/>
</mx:Application>
The source attribute of the <mx:Script> tag supports both relative and absolute paths. For more information, see “Referring to external files” on page 51.
You cannot use the tag. To include a file and write ActionScript in the MXML file, use two
source attribute and wrap ActionScript code inside the same <mx:Script>
<mx:Script> tags.
Using ActionScript in Flex applications 49
Using the #include directive
The
#include directive is an ActionScript statement that copies the contents of the specified file
into your MXML file. The
#include "file_name"
#include directive uses the following syntax:
The following example includes the myfunctions.as file:
<mx:Script>
<![CDATA[
#include "myfunctions.as"
... ]]>
</mx:Script>
Note: The semicolon. If you do, you get a “Malformed surround the target file with quotation marks.
#include directive is a special kind of ActionScript statement. Do not end the line with a
#include directive” error message. In addition, you must
You can only specify a single file for each #include directive, but you can use any number of
#include directives. You can next #include directives; files with #include directives can include
files that have
The
#include directive supports only relative paths. For more information, see “Referring to
#include directives.
external files” on page 51.
You can only use the
#include where multiple statements are allowed. For example, the following
is not allowed:
if (expr)
#include "foo.as" // First statement is guarded by IF, but the rest are not.
...
The following is allowed:
if (expr) {
#include "foo.as" // All statements inside { } are guarded by IF.
}
The use of curly braces ({ }) allows multiple statements because you can add multiple statements inside the braces.
Macromedia recommends against using the
#include directive if you use a large number of
included ActionScript files. You should try to break the code into separate class files where appropriate and store them in logical package structures.
50 Chapter 3: Using ActionScript
Referring to external files
The
source attribute of the <mx:Script> tag and the #include directive refer to files in
different ways.
The following are the valid paths to external files that are referenced in an
source attribute:
<mx:Script> tag’s
Absolute URLs, such as http://www.macromedia.com or file:///C|/site_flashteam/foo.gif.
Site-relative URLs, such as /scripts/myscript.as. A URL that begins with a slash is resolved
relative to the context root of the application. The default application root is /flex_app_root.
Relative URLs, such as ../myscript.as. A relative URL that does not start with a slash is resolved
relative to the file that uses it. If the tag included in “mysite/myfiles/myapp.mxml”, then the system searches for “mysite/IncludedFile.as”.
For an ActionScript
#include directive, you can only reference relative URLs. You can specify file
locations relative to the context root (start the location with a slash) or relative to the document root (omit the leading slash), as the following example shows:
#include "/myfiles/functions.as" // Relative to the context root. Resolves to
#include "functions.as" // Relative to the current document root (in this case,
// in the same directory as the current document).
Flex searches the ActionScript classpath for imported classes and packages. Flex does not search the ActionScript classpath for files that are included using the attribute of the
<mx:Script> tag.
Importing classes and packages
If you create many utility classes or include multiple ActionScript files to get at commonly used functions, you might want to store them in a set of classes in their own package. You can import ActionScript classes and packages using the explicitly enter the fully qualified class names when accessing classes within ActionScript.
The following example imports the MyClass class in the MyPackage.Util package:
<mx:Script>
import MyPackage.Util.MyClass; ...
</mx:Script>
In your ActionScript code, instead of referring to the class with its fully qualified package name (MyPackage.Util.MyClass), you can refer to it as MyClass, as the following example shows:
import MyPackage.Util.MyClass; function createClass() { tObj = new MyClass; }
Note: All statements other than import and variable declarations must be inside functions in an
<mx:Script> tag.
<mx:Script source="../IncludedFile.as"> is
// /flex_app_root/myfiles/functions.as
#include directive or the source
import statement. By doing this, you do not have to
Using ActionScript in Flex applications 51
You can also use the wildcard character (*) to import all the classes in a given package. For example, the following statement imports all classes in the MyPackage.Util package:
import MyPackage.Util.*;
Flex searches the ActionScript classpath for imported files and packages.
If you import a class but do not use it in your application, the class is not included in the resulting SWF file’s bytecode. As a result, importing an entire package with a wildcard does not create an unnecessarily large SWF file.

About the ActionScript classpath

ActionScript classes that you use in your applications must be in a directory that is in the ActionScript classpath. By default, the flex_app_root/WEB-INF/flex/user_classes directory is part of the ActionScript classpath. In addition, ActionScript classes can be in the same directory or subdirectories as the MXML file. ActionScript classes can also be in component SWC files.
The order of the classpath entries is important. When Flex encounters classes that share the same name, it uses the class that it found first in the classpath. The rest are ignored.
Flex loads ActionScript classes in the following order:
1.
Local *.as files in the same directory or subdirectories as the currently executing application.
2.
Classes in flex_app_root/WEB-INF/flex/user_classes.
3.
Classes specified the <actionscript-classpath> tag in the flex-config.xml file.
4.
Classes defined in components (SWC files) used by the currently executing application.
This includes the SWC files in the frameworks and frameworks_debug directories, as well as custom components. Directories containing accessible SWC files are defined by the
<compiler> tag’s <lib-path> entries in the flex-config.xml file. For more information, see
Developing Flex Applications.
You can add additional directories to the Flex ActionScript classpath with the child tag of the
<actionscript-classpath> tag in the flex-config.xml file. Flex searches for
<path-element>
classes in the order in which they appear in this list.
The following example shows the default user_classes directory and two additional directories added to the ActionScript classpath:
<compiler>
<actionscript-classpath>
<path-element>/WEB-INF/flex/user_classes</path-element>
<path-element>/WEB-INF/flex/3rd_party_packages</path-element>
<path-element>/WEB-INF/flex/test_dir</path-element> </actionscript-classpath>
</compiler>
For more information on the <compiler> settings, see Chapter 39, “Administering Flex,” in Developing Flex Applications.
52 Chapter 3: Using ActionScript

Creating ActionScript components

You create reusable components using ActionScript, and reference these components in your Flex applications as MXML tags. Components created in ActionScript can contain graphical elements, define custom business logic, or extend existing Flex components. They can inherit from any components available in Flex.
Defining your own components in ActionScript has several benefits. Components let you divide your applications into individual modules that you can develop and maintain separately. By implementing commonly used logic within custom components, you can build a suite of reusable components that you can share among multiple Flex applications.
In addition, you can base your custom components on the set of Flex components by extending from the Flex class hierarchy. You can create custom versions of Flex visual controls, as well as custom versions on nonvisual components, such as data validators, formatters, and effects.
For example, you can define a custom button, derived from the Flex Button control, as the following example shows:
class myControls.MyButton extends mx.controls.Button {
function MyButton() {
... } ...
}
In this example, you write your MyButton control to the MyButton.as file, and you store the file in the myControls subdirectory of the root directory of your Flex application. The fully qualified class name of your component reflects its location. In this example, the component’s fully qualified class name is
myControls.MyButton.
You can reference your custom Button control from a Flex application file, such as MyApp.mxml, as the following example shows:
<mx:Application xmlns:mx="http://www.macromedia.com/2003/mxml"
xmlns:cmp="myControls.*" >
<cmp:MyButton label="Jack" />
</mx:Application>
In this example, you first define the cmp namespace that defines the location of your custom component in the application’s directory structure. You then reference the component as an MXML tag using the namespace prefix.
Typically, you put custom ActionScript components in directories that are in the ActionScript classpath. These include your application’s root directory, the flex_app_root/WEB- INF/flex/user_classes directory, or any directory you specify in the
<actionscript-classpath>
tag in the flex-config.xml file. For more information, see Chapter 18, “Creating ActionScript Components” in Developing Flex Applications.
Creating ActionScript components 53

Types of custom components

You can create the following types of components in ActionScript:
User-interface components User-interface components contain both processing logic and
visual elements. These components usually extend the Flex component hierarchy. You can extend from the UIObject and UIComponent classes, or any of the Flex components, such as Button, ComboBox, or DataGrid. Your custom ActionScript component inherits all of the public methods and properties of its parent class.
Nonvisual components Nonvisual components define no visual elements. By definition, a
nonvisual component is an ActionScript class that does not extend the UIObject, UIComponent, or MovieClip classes. Using nonvisual components can provide greater efficiency at runtime.

Techniques for separating ActionScript from MXML

This section follows a single sample application and shows how it uses several different methods of separating ActionScript from the MXML. The Temperature application takes input from a single input field and uses a function to convert the input from Farenheit to Celsius. It then displays the resulting temperature in a Label control.
The following figure shows the sample Temperature application:
There are several ways to separate MXML and ActionScript in this simple application that calls a single function:
One MXML document (ActionScript event handling logic in MXML tag)
One MXML document (function call in MXML tag event)
One MXML document and one ActionScript file
One codeless MXML document and one ActionScript component
The following sections describe these methods.

One MXML document (ActionScript event handling logic in MXML tag)

The following code shows the ActionScript event handling logic inside the MXML tag’s event:
<?xml version="1.0"?> <mx:Application xmlns:mx="http://www.macromedia.com/2003/mxml">
<mx:Panel title="My Application" marginTop="10" marginBottom="10"
marginLeft="10" marginRight="10" >
<mx:HBox>
<mx:Label text="Temperature in Farenheit:"/> <mx:TextInput id="farenheit" width="120"/>
54 Chapter 3: Using ActionScript
click
<mx:Button label="Convert"
click="celsius.text=(farenheit.text-32)/1.8;" />
<mx:Label text="Temperature in Celsius:"/> <mx:Label id="celsius" width="120" fontSize="48"/> </mx:HBox>
</mx:Panel>
</mx:Application>

One MXML document (function call in MXML tag event)

The logic for the function is inside an from the MXML tag’s
<?xml version="1.0"?> <mx:Application xmlns:mx="http://www.macromedia.com/2003/mxml">
<mx:Script>
<![CDATA[
function calculate() {
celsius.text=(farenheit.text-32)/1.8;
}
]]>
</mx:Script>
<mx:Panel title="My Application" marginTop="10" marginBottom="10"
marginLeft="10" marginRight="10" >
<mx:HBox>
<mx:Label text="Temperature in Farenheit:"/>
<mx:TextInput id="farenheit" width="120"/>
<mx:Button label="Convert" click="calculate();" />
<mx:Label text="Temperature in Celsius:"/>
<mx:Label id="celsius" width="120" fontSize="48"/> </mx:HBox>
</mx:Panel>
</mx:Application>
click event, as the following code shows:
<mx:Script> block in the MXML document, and is called

One MXML document and one ActionScript file

The function call is in an MXML tag event, and the function is defined in a separate ActionScript file, as the following code shows:
<?xml version="1.0"?> <mx:Application xmlns:mx="http://www.macromedia.com/2003/mxml">
<!-- Specify the ActionScript file containing the function. -->
<mx:Script source="sample3script.as"/>
<mx:Panel title="My Application" marginTop="10" marginBottom="10"
marginLeft="10" marginRight="10" > <mx:HBox>
<mx:Label text="Temperature in Farenheit:"/>
<mx:TextInput id="farenheit" width="120"/>
<mx:Button label="Convert" click="calculate();" />
<mx:Label text="Temperature in Celsius:"/>
<mx:Label id="celsius" width="120" fontSize="48"/>
Techniques for separating ActionScript from MXML 55
</mx:HBox>
</mx:Panel>
</mx:Application>
The sample3script.as ActionScript file contains the following code:
function calculate() {
celsius.text=(farenheit.text-32)/1.8;
}

One codeless MXML document and one ActionScript component

The following example uses an ActionScript class as a controller component. The ActionScript component is declared in the application using a custom MXML tag. To use the TempConverter component in an application, you call its of the
<mx:Application> tag, as the following code shows:
<?xml version="1.0"?> <mx:Application xmlns:mx="http://www.macromedia.com/2003/mxml"
initialize="converter.setupListener()">
<local:TempConverter id="converter" xmlns:local="*"/>
<mx:Panel title="My Application" marginTop="10" marginBottom="10"
marginLeft="10" marginRight="10" > <mx:HBox>
<mx:Label text="Temperature in Farenheit:" />
<mx:TextInput id="farenheit" width="120" />
<mx:Button id="myButton" label="Convert" />
<mx:Label text="Temperature in Celsius:" />
<mx:Label id="celsius" width="120" fontSize="24" /> </mx:HBox>
</mx:Panel>
</mx:Application>
setupListener() method in the initialize property
The TempConverter.as ActionScript class contains the following code:
class TempConverter implements mx.core.MXMLObject{
public var view;
function initialized(doc : Object, id : String) : Void {
view = doc;
}
function setupListener() : Void {
view.myButton.addEventListener("click", this);
}
function click(event) {
view.celsius.text=(view.farenheit.text-32)/1.8;
}
}
TempConverter is an MXMLObject and the compiler calls the initialized() method on all instances of MXMLObject.
56 Chapter 3: Using ActionScript
CHAPTER 4

Architecting Flex Applications

This chapter describes the Macromedia Flex development process. It describes coding practices, multitier applications, and application architecture. It also includes information about MXML URL parameters, the Flex development environment, and Flex development tools.
When you develop a Flex application, you use the same iterative process that you use for other types of web application files, such as HTML, JavaServer Pages (JSP), Microsoft Active Server Pages (ASP), and Macromedia ColdFusion Markup Language (CFML). Unlike a set of static HTML pages or HTML templates created using JSP, ASP, or CFML, the files in a Flex application are compiled into a single binary SWF file. JSP, ASP, and ColdFusion are templating systems in which application processing occurs on the server and data is dynamically added to an HTML template and delivered to the client in an HTML page.

Contents

About the Flex coding process . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58
Working with a multitier application model. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62
Improving application start-up time and performance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67
Architecting an application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70
Summary of Flex application features. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79
57

About the Flex coding process

Creating a useful Flex application is as easy as opening your favorite text editor, typing some XML tags, saving the file, opening the file’s URL in a web browser, and then repeating the process. When you develop a Flex application, you use the same iterative process that you use for other types of web application files, such as HTML, JSP, ASP, and CFML.
Unlike a set of static HTML pages or HTML templates created using JSP, ASP, or CFML, the files in a Flex application are compiled into a single binary SWF file. Another major difference between a Flex application and a JSP, ASP, or ColdFusion application is that application logic resides in the client-side SWF file. JSP, ASP, and ColdFusion are templating systems in which application processing occurs on the server and data is dynamically added to an HTML template and delivered to the client in an HTML page. For more information, see “Moving to Flex from
HTML” on page 58 and “Moving to Flex from an HTML templating environment” on page 59.
Because MXML files are ordinary XML files, you have a wide choice of development environments. You can develop in a simple text editor, a dedicated XML editor, or an integrated development environment (IDE) that supports text editing. Flex also provides tools for code debugging and performance profiling; for more information, see “Using Flex development tools”
on page 60.

Moving to Flex from HTML

Although similar in some ways, developing a Flex application is significantly different from developing in HTML. HTML uses a page metaphor in which code is primarily written in a set of page files. What constitutes an application is really a set of separate HTML pages. Each page must be requested from the server and displayed individually. Assets such as images are loaded into the individual page that uses them when the page is requested. During development, you write code, save it, and display a page in a web browser.
The code for a Flex application is likely to be contained in more than one file to promote reusability, extensibility, and modularity. However, when the top-level MXML file is requested, the Flex server compiles that file and all the other files it depends on into a single SWF file. Once the application SWF file is generated, the server does not recompile it unless the source code changes. The files that make up the application are compiled into the SWF file; however, the application can request data from external data sources at runtime. During development, you write code, save it, and display the entire application in a web browser.
Although Flex development is quite different from HTML development, you can easily incorporate a Flex application into an HTML page. To do so, you specify the name of a SWF file with the same prefix as the MXML file but a suffix of mxml.swf in standard HTML and
<embed> tags, as the following example shows:
<object classid='clsid:D27CDB6E-AE6D-11cf-96B8-444553540000'
codebase='http://download.macromedia.com/pub/shockwave/cabs/flash/
swflash.cab#version=7,0,0,0' width='600' height='600'>
<param name='src' value='CreditCard.mxml.swf'> <embed pluginspage='http://www.macromedia.com/go/getflashplayer'
width='600' height='600 src='CreditCard.mxml.swf' /> </object>
58 Chapter 4: Architecting Flex Applications
<object>
The first time the HTML page is requested, the Flex application is compiled into a SWF file with the specified name. If the MXML file changes, the Flex compiler recompiles the MXML file the next time that the HTML page is requested. For more information, see Chapter 38, “Using the Flex JSP Tag Library,” in Developing Flex Applications.

Moving to Flex from an HTML templating environment

In contrast to environments like JSP, ASP, and ColdFusion, Flex is not a templating system. MXML files are not templates that contain rules processed on the server to return a filled-in template. Instead, MXML code is compiled into a fully formed client application that is able to process server-side logic, and change what is displayed using its own client-side logic.
A Flex application does not go to the server every time the user interface must change or an event must be handled. Presentation logic and logic for server-side requests and responses is on the client in the SWF file that is generated when the user initially requests the MXML file. In Flex, changes to the user interface occur on the client, based on client-side code execution.
A Flex application makes HTTP requests to contact external data services, such as web services; this interaction with the server does not require you to refresh the application.

Moving to Flex from Macromedia Flash MX

Developing a Flex application is very different from developing an application in Macromedia Flash MX, even though in both environments the application is compiled into a SWF file. You create a Flex application in text files, which you can create and edit in a simple text editor or a more sophisticated development environment. You publish Flex application source files to a Java web application, and the files are compiled into a SWF file when a user requests the application­level MXML file. If you change the application’s source code, it is recompiled into a SWF file the next time it is requested.
You create a Flash document file (an FLA binary file) in the Flash MX visual authoring environment, and save it as a SWF file before publishing it to a website; it is usually referenced inside an HTML page. Flash MX uses concepts such as the Timeline, animation frames, and layers for organizing and controlling an application’s content over time. In Flex, you write the declarative parts of an application, such as user-interface components and connections to data sources, in MXML tags. You must use the tags in the proper hierarchy within the application, but there is no external notion of Timelines, frames, or layers. Just by using a few MXML tags, you can create a useful application with built-in behavior.
Although the development models for Flash MX and Flex are different, Flash MX is a powerful tool for creating custom components and visual assets that you can use in Flex applications. You can export files created in Flash MX in component package files called SWC files, which you can reference as custom tags in MXML files. You can also use the MXML
<mx:Loader> tags to import SWF files into a Flex application.
<mx:Image> and
About the Flex coding process 59

About the Flex development environment

You store Flex server code and application files in the directory structure of a standard web application on a J2EE-compliant application server. The MXML deployment model is similar to that of JavaServer Pages (JSPs). You create an MXML file in the text editor of your choice, and place it in a web application directory that is accessible from a web browser. For example, you can place MXML files in the web application root directory or a subdirectory other than the reserved WEB-INF directory.
The directory structure of a typical Flex-enabled web application looks like the following:
Directory Description
web_app
(root directory or WAR root)
/WEB-INF Contains the standard web application deployment descriptor
/WEB-INF/flex Contains Flex configuration files.
/WEB-INF/flex/system-classes Contains ActionScript standard library stub classes that Flex use
/WEB-INF/flex/user_classes Contains custom ActionScript classes and MXML components.
/WEB-INF/lib Contains Flex server code in Java Archive (JAR) files.
/WEB-INF/flex/frameworks Contains the SWC component file, builtin.swc, that contains the
Contains the WEB-INF directory and all files that must be accessible by the user’s web browser, such as MXML files, JSPs, HTML pages, Cascading Style Sheets, images, and JavaScript files. You can place these files directly in the web application root directory or in arbitrary subdirectories that do not use the reserved name WEB-INF.
(web.xml) that configures Flex. This directory might also contain a vendor-specific web application deployment descriptor.
internally for type-checking.
Flex application framework files.

Using Flex development tools

Flex provides the following tools to help you test, debug, and tune your applications during the development process. To use these tools, the flex/flex-config.xml file must be
<production-mode>false</production-mode>
false (the default):
<production-mode> setting in the .../WEB_INF/
If <production-mode> is set to true, Flex disables all debugging and profiling features. Flex also ignores query string parameter overrides such as
<production-mode> is enabled.
60 Chapter 4: Architecting Flex Applications
?debug=true and ?asprofile=true when
The following table describes the Flex development tools:
Tool Description
Macromedia Flash Debug Player Flash Debug Player is a Flash Player that reports runtime errors,
including errors for undeclared variables, uncaught runtime exceptions, and operating-system–specific networking errors. You can view errors in a trace window and send errors to a text file. When you run Flash Debug Player, you specify the subsystems to monitor and request the compiled SWF file, through the Flex server. To use the Flash Debug Player, you must disable production mode if it is enabled and edit debugging settings in the flex­config.xml file. For more information, see Chapter 36, “Debugging Flex Applications,” in Developing Flex Applications.
command-line debugger The Flex ActionScript debugger lets you step into and debug
ActionScript files used by your Flex applications. To use the command-line debugger, you must disable
production mode if it is enabled and edit debugging settings in the flex-config.xml file. For more information, see Chapter 36, “Debugging Flex Applications,” in Developing Flex Applications.
compc The compc utility generates a SWC file from MXML component
source files and/or ActionScript component source files.
mxmlc The Flex command-line compiler, mxmlc, is useful if you want to
request SWF files in a web browser or in Flash Player. It is particularly useful for debugging SWF files with Flash Debug Player.
For more information, see Chapter 39, “Administering Flex,” in Developing Flex Applications.
ActionScript Profiler The ActionScript Profiler monitors ActionScript performance in
Flash Debug Player. It has a JSP-based user interface and also provides text-based performance reports. For more information, see Chapter 37, “Profiling ActionScript,” in Developing Flex Applications.
You can get additional information about Flex applications during the development process using a set of query string parameters. You append these to the end of the request string, as the following example shows:
http://localhost:8700/flex/MyApplication.mxml?debug=true
To use most of these query string parameters, you must disable production mode in the flex­config.xml file by setting the value of the
<production-mode> tag to false.
About the Flex coding process 61
The following table describes the query string parameters that you can use to get additional information:
Query parameter Description
?accessible=true
?asprofile=true
?debug=true
?errors=true
?networkCapturePort=portnumber
?proxyUrl=urlvalue
?showAllWarnings=true
?showBindingWarnings=true
Adds screen reader accessibility to all components that are capable of accessibility. Available when
true or false.
Generates ActionScript profiling information.
Enables ActionScript debugging for an application. Overrides the
debug setting for all applications set in the flex-config.xml file.
The process-debug-query-params value in the flex-config.xml file must be set to
Returns errors and warnings in an XML document; does not return a SWF file. Used primarily by authoring tools.
(Used only by authoring tools) Redirects requests.
Specifies a web service proxy URL. Available when production-
mode
is set to true or false. The allow-url-override value in the
flex-config.xml file must be set to
?proxyUrl=urlvalue.
Displays warning messages.
Displays warnings about data bindings. The
showBindingWarnings parameter is a subset of the showAllWarnings parameter. If showAllWarnings is set to true,
binding warnings are enabled. If setting
showBindingWarnings to true enables binding warnings.
true when using ?debug=true.
production-mode is set to
true when using
showAllWarnings is set to false,
For more information about application configuration, see Chapter 39, “Administering Flex,” in Developing Flex Applications.

Working with a multitier application model

In MXML, you use tags to declare an application’s user interface. You also use tags to declare an application’s data management tier, which represents connections to data sources, data requests and responses, data storage, binding of data between the user interface and data sources, data validation, and data formatting. Using just tags, you get a great deal of built-in code execution that ties the user interface to the data management tier. You can also write ActionScript code that executes at runtime based on user interaction or system events.
62 Chapter 4: Architecting Flex Applications

Laying out your application

You declare a Flex user interface by using tags that represent user-interface components. There are two general types of components: controls and containers. Controls are form elements, such as buttons, text fields, and list boxes. Containers are rectangular regions of the screen that contain controls and other containers. Every user-interface component has a corresponding ActionScript class that inherits common functionality from the mx.core.UIObject and mx.core.UIComponent base classes. User-interface components contain properties, methods, and events. For more information, see Chapter 1, “Using Flex Components,” in Developing Flex Applications.
At the root of a Macromedia Flex application is a single container, called the Application container, that represents the entire Flash Player drawing surface. This Application container holds all other containers, which can represent dialog boxes, panels, and forms.
A container has predefined rules to control the layout of its child containers and controls, including sizing and positioning. Flex defines layout rules to simplify the design and implementation of rich Internet applications, while also providing enough flexibility to let you create a diverse set of applications.
One advantage of having predefined layout rules is that your users will soon grow accustomed to them. That is, by standardizing the rules of user interaction, your users will not have to think about how to navigate the application, but can instead concentrate on the content that the application offers.
Another advantage is that you do not have to spend time defining navigation and layout rules as part of the design process. Instead, you can concentrate on the information that you want to deliver and the options that you want to provide for your users, and not worry about implementing all the details of user action and application response. In this way, Flex provides the structure that lets you quickly and easily develop an application with a rich set of features and interactions.

Organizing your data

The Flex data management tier consists of the features in the following table.
Feature Description
Data service Accesses data from a remote location, and sends new or modified data to a remote
Data model Stores data in fields that represent each part of a specific data set. For example, a
Data validator Validates data in data model fields. For example, you can use a data validator to
location. A typical way to send data to a data service is by sending data stored in a user interface control to the data service. For example, a user fills in the fields of a form and clicks a button to submit the form to a service. The user input data becomes part of the service request. Data that the service returns is stored in the service’s
person model stores data such as a person’s name, age, and phone number. Data services contain data models to store request data and result data.
validate the data in a form before submitting it to a data service.
result property.
Working with a multitier application model 63
Feature Description
Data formatter Converts raw data to a formatted string. Formatters are triggered just before data is
Data binding Copies data stored in one object to another object. For example, you can bind data
displayed in a text field. They can save you time by automating data formatting tasks, and by letting you easily change the formatting of fields within your applications.
from the fields of a user input form to fields in a data service request. To display data that a data service returns, you can bind fields from the data service result to user interface controls.
Separating your data model from your view
To cleanly separate the user interface, application-specific data, and data services, you can use Flex data models that store data between controls and data services. This type of three-tier design is applicable to both input data and data service results.
When you plan an application, you determine the kinds of data that the application must store and how that data must be manipulated. This helps you decide what types of data models you need. For example, suppose you decide that your application must store data about employees. A simple employee model might contain name, department, and e-mail address properties.
A Flex data model is an ActionScript object that contains properties that you use to store application-specific data. You can use a data model for data validation, and it can contain client­side business logic. You can define a data model in MXML or ActionScript. In the model-view­controller (MVC) design pattern, the data model represents the model tier.
You can define a data model in an MXML tag, ActionScript function, or an ActionScript class. A model written in MXML is useful for rapid development and simple data storage, but it does not provide any additional functionality, and you cannot set the data types of the model’s properties. You should use an ActionScript-based class if you want to set data types and provide methods for additional functionality. In general, you should use MXML-based models for simple data structures and use ActionScript for more complex structures and client-side business logic.
Working with data services
Flex is designed to interact with several types of services that provide access to local and remote server-side logic. For example, a Flex application can connect to a web service that uses the Simple Object Access Protocol (SOAP), a Java object residing on the same application server as Flex using AMF, or an HTTP URL that returns XML. AMF is the protocol used in Flash Remoting MX. The MXML components that provide data access are called data service components. MXML includes the following types of data service components:
WebService provides access to SOAP-based web services.
HTTPService provides access to HTTP URLs that return data.
RemoteObject provides access to Java objects (Java Beans, EJBs, POJOs) using the AMF
protocol.
64 Chapter 4: Architecting Flex Applications
How you choose to access data in your Flex application impacts performance. Because a Flex application is cached on the browser after the first request, data access is responsible for significantly affecting performance while the application runs. Flex provides several solutions for data delivery to the client. It delivers data through runtime services that invoke Java classes loaded in the Flex classpath, or sends proxy requests to web services or HTTP servers.
Using the WebService component enables you to use a SOAP-based approach, but it does not always yield the best performance. Also, there is extra overhead for the additional XML with the SOAP encoding when compared to AMF. On average, AMF is three times faster than SOAP and, with very large payloads, can be up to six times faster. This is because AMF uses a binary protocol that greatly reduces the size of the payload compared to XML-based soap packets for the same data.
The performance of SOAP with web services is also dependent on your web services implementation. Different application servers use different web service back ends, so you might see performance differences depending on the implementation. The only way to understand how well your implementation will perform is to load-test your services.
Many times, the choice depends on your existing applications and how you choose to integrate them with your back end server-side resources. The performance of web services depends greatly on your application server’s underlying implementation of the web services engine, so you should load-test to see how well it performs.

Controlling runtime code execution

Flex uses an event-driven application model, which is manifested in both user interaction with the user interface and code execution based on system events. For more information about events, see Chapter 16, “Working with ActionScript in Flex,” in Developing Flex Applications.
Using events to handle user interaction
User interface controls have event properties to which you can assign functions, called event handlers, that respond to events. The following example shows a simple event handler that displays text in a TextArea control when the user clicks a Button control:
<mx:Script>
<![CDATA[
function Hello() {
text1.text="Hello!";
}
]]> </mx:Script>
<mx:Button label="Clear" click="Hello();" > <mx:TextArea id="text1" width="150" text="This will be cleared" />
Working with a multitier application model 65
Using events to connect application functionality
ActionScript code executes asynchronously. This means that code in a Flex application continues executing without being blocked by the execution of other code. However, you need a way to deal with dependencies between the execution of different pieces of code in an application. There are times when you do not want a function to execute until some other function has already executed. You can use event handling for these dependencies.
For example, you might have one web service operation that uses data that another operation returns. A result event is triggered when a web service operation successfully returns a result. You can write a function that calls the second operation with the result of the first operation, and then assign that function as the result event handler of the first operation, as the following example shows. You can use this technique for any code that depends on the execution of other code.
... <mx:WebService id="myService"...> <mx:operation name="getFoo" result="myFooResultHandler(event.result)" /> <mx:operation name="getBarWithFooInput" /> </mx:WebService>
<mx:Script>
<![CDATA[
function myFooResultHandler(foo) {
myService.getBarWithFooInput(foo);
}
]]> </mx:Script> ...
For more information about event handling, see Chapter 16, “Working with ActionScript in Flex,” in Developing Flex Applications.
Using events to handle errors
Just as you can use events to connect application functionality, you can also use them to handle errors. Flex data services contain a fault event that is triggered when a data service has a problem returning result data. You can write an ActionScript event handler function that responds to fault events. The following example shows how you specify a fault event handler for a web service operation:
<mx:Script>
<![CDATA[
function showErrorDialog(error){
// Function implementation...
}
]]> </mx:Script> ... <mx:WebService id="WeatherService" ...">
<mx:operation name="getFoo" fault="showErrorDialog(event.faultString);"/
> </mx:WebService>
66 Chapter 4: Architecting Flex Applications

Controlling application appearance

Flex defines a default “look and feel” (appearance) that you can use as-is in an application, or modify to define your own specific appearance. As part of modifying the appearance, you can change some or all of the following:
Styles Set of characteristics, such as font, font size, text alignment, and color. These are the
same styles as defined and used with Cascading Style Sheets (CSS). For more information, see Chapter 20, “Using Styles and Fonts,” in Developing Flex Applications.
Skins Symbols that control a component’s appearance. For more information, see Chapter 20,
“Using themes and skins,” in Developing Flex Applications.
Behaviors Visible or audible changes to a Flex component triggered by an application or user
action. Examples of behaviors are moving or resizing a component based on a mouse click. For more information, see Chapter 21, “Using Behaviors,” in Developing Flex Applications.
Sizes Height and width of a component or application. All components have a default size.
You can use the default size, specify your own size, or let Flex resize a component as part of laying out your application. For more information, see Chapter 4, “Introducing Containers,” in Developing Flex Applications.
Enabling application zooming in Flash Player
By default, the zoom feature of Flash Player is disabled for Flex applications. You can enable zooming for individual applications using a function like the one in the following example. Write the function in an of the
<mx:Application> tag.
<mx:Application width="600" height="400"
xmlns:mx="http://www.macromedia.com/2003/mxml" initialize="initMyApp();">
<mx:Script> tag, and specify it as the event handler for the initialize event
<mx:Script>
<![CDATA[
function initMyApp(){
var myMenu=new ContextMenu(); myMenu.builtInItems.zoom = true; document.menu=myMenu;
}
]]> </mx:Script> ... </mx:Application>

Improving application start-up time and performance

This section describes some very simple things that you can take to improve application start-up time. For more information, see Chapter 27, “Improving Layout Performance,” in Developing Flex Applications.
During the Flex product life cycle, Macromedia will provide additional information about performance on the Macromedia website (see www.macromedia.com/go/flex).
Improving application start-up time and performance 67

Using layout containers

You can improve application start-up time by using Canvas containers, instead of relative layout containers, such as the Form, HBox, VBox, Grid, and Tile containers, to perform automatic layout. Canvas containers eliminate the layout logic that containers use to perform automatic positioning of their children at startup, and replaces it with explicit pixel-based positioning. When using a Canvas container, you must remember to explicitly set the x and y positions of all of its children. If you do not set x and y positions, the Canvas container’s children lay out on top of each other at the default x, y coordinates (0,0). Macromedia recommends that developers use the relative layout containers initially, and move to using Canvas containers as warranted by performance testing.

Improving initial layout performance

Every container has a
creationPolicy property that determines how the container decides
which of its descendants, if any, to create when the container is created. Flex uses this property to determine when components are created when an application starts.
You can instruct Flex to create all components in all containers, only the initially-visible components in the containers, or no components in any of the containers. In addition, you can define the order in which Flex creates containers and their components.
By using the
creationPolicy property, you can decide at what stages the user incurs the costs of
creating components. For more information, see Chapter 27, “Improving Layout Performance,” in Developing Flex Applications.

Nesting containers

Application start-up time slows commensurate with the complexity of the layout of your Flex application. Excessive levels of nested containers can contribute to this complexity, and should be avoided if you can accomplish the same layout with fewer levels of nesting. Try using margin, gap, and alignment properties and the Spacer control, to achieve the desired layout.
When you have a working skeleton of your application, consider the containers that you are using to determine if you could use alternate containers with less nesting. For example, consider the following layout:
<mx:Grid>
mx:GridRow>
<mx:GridItem>
<mx:Button label="Visa"/> </mx:GridItem> <mx:GridItem>
<mx:Button label="MasterCard"/> </mx:GridItem> <mx:GridItem>
<mx:Button label="Diner's Club"/> </mx:GridItem> <mx:GridItem>
<mx:Button label="AmEx"/> </mx:GridItem>
</mx:GridRow>
</mx:Grid>
68 Chapter 4: Architecting Flex Applications
You could replace the previous layout with the following layout to achieve the same effect:
<mx:VBox>
<mx:Button label="Visa"/> <mx:Button label="MasterCard"/> <mx:Button label="Diner's Club"/> <mx:Button label="AmEx"/>
</mx:VBox>

Improving effect performance

If animations in an application do not play smoothly, background processing might be interfering with the animation. Effects have a public property called When this property is
true, it blocks all background processing while the effect is playing,
including measurement and layout and data service response. The default value is should be careful when you set this property to
true because it makes an effect completely
suspendBackgroundProcessing.
false. You
uninterruptible while playing.
Large-scale transition effects applied to complex views can affect how quickly the player can redraw the view. When this happens, you will notice the effect does not play smoothly. The following tips describe ways to modify an application to make effects play more evenly:
Increase the duration of an effect to spread out the distinct, jerky stages over a longer period of
time, which allows the eye to fill in the differences.
Hide part of the application that is playing an effect to make the effect play more smoothly,
because there is less for Flash Player to redraw. To do this, you use the
effectEnd events to control what is visible before and after the effect. For example, if you
apply a Fade effect to a Form with many controls, you can use the some of the less important controls invisible, have the Form container play the Fade effect, and then use the
effectEnd event to make the controls visible again.
effectStart and
effectStart event to make
Use a solid backgroundColor to improve an effect’s performance. If you want a slight gradient
instead of a solid color, use a bitmap image. Using bitmap images in backgrounds can slow down effects. Designers often give their views a
backgroundImage that is a solid colors with gradients or patterns.
backgroundImage that is a SWF file or an SVG file instead of a

Using a wait state animation

When the child containers of navigator containers are heavily populated, users experience a wait period when they navigate to a new view. You can create an animation to indicate this fact. The extras directory of the flex.war file includes a sample application with a TabNavigator container that displays a precompiled SWF animation during wait states. View the source of the app.mxml file in the extras/NavigatorWaitState directory of your Flex installation to see how the TabNavigator container catches the symbol. When the child views broadcast their
change event and displays the embedded SWF file as a wait
draw events, indicating they have finished drawing
their contents, the TabNavigator container destroys the wait symbol.
Improving application start-up time and performance 69

Displaying multiple pop-up windows

Having more then six heavily populated pop-up windows open at the same time in a Flex application can affect performance. The performance of Flash Player is limited by how quickly it can redraw obscured windows. This is even more of an issue if each window has a complex hierarchy of components within it. The more components that are obscured, the longer it takes the player to redraw.
One possible way to work around this is to use Navigator containers to organize your pop-up content so that it is spread out over multiple child views; for more information, see Chapter 7, “Using Navigator Containers,” in Developing Flex Applications. You can also organize multiple pop-up windows in a dashboard application using Panel containers; for more information about Panel containers, see Chapter 6, “Using Layout Containers,” in Developing Flex Applications.

Using Flash Debug Player

Using Flash Debug Player can potentially slow an application. As Flash Debug Player processes the application, it simultaneously writes out trace statements and warnings. If your application runs quickly in Flash Debug Player, it will run as fast or faster in the standard Flash Player.
You can have both the Flash Debug Player and the standard Flash Player installed on your system. Use query parameters and settings in the flex-config.xml file to control which player Flex uses to execute your application. Ensure that you use the standard Flash Player during performance testing. For more information, see Chapter 36, “Debugging Flex Applications,” in Developing Flex Applications.

Architecting an application

After you determine the purpose and general features of an application, you need to consider the following topics:
What the object model should be
What types of Flex components you should use to represent the object model
What type of messaging strategy you should use to pass data between objects
This section uses a fairly simple e-commerce application called the Flex Store to illustrate general ways to approach object models, component types, and messaging strategies. The application demonstrates clear separation of model and view objects, and loose coupling of components. It uses a combination of standard Flex components, MXML components, SWC components, and ActionScript components.
The purpose of the Flex Store application is to display a catalog of items that the user can add to a shopping cart, and then order. The following list includes some of the things a user can do with the application:
Click a product thumbnail image to display a larger image and description.
Select a price range for products.
Add items to the shopping cart.
Place orders in a checkout form.
70 Chapter 4: Architecting Flex Applications
The Flex Store application is included in the samples.war file, which you can extract into your application server.
The following figure shows the catalog and shopping cart views of the Flex Store application:

Developing an object model

The object model defines how the various parts of the application map to individual objects. It is useful to think in terms of a model-view-controller (MVC) architecture, and consider whether a particular object is part of the model, view, or controller tier. The MVC design pattern decouples data access, business logic, and data presentation and user interaction.
The following sections describe the object model of the Flex Store application.
Architecting an application 71
Flex Store object model figure
The following figure shows the object model for the Flex Store application and identifies each object as part of the model, view, or controller:
FlexStore
ShoppingCart
Model
View
catalog
Model
CartView
View
ProductThumbnail
View
Thumbnail
View
ProductDetail
View
Checkout
View
FlexStore
The FlexStore object is the top-level object in the Flex Store application. It contains the rest of the application objects, including the standard Flex objects and custom objects. This object is a view object because it is the top-level object in the user interface, but it also contains the rest of the application.
catalog
The catalog object is a nonvisual object that contains data about the products available for purchase. This object is a model object because its primary purpose is to represent products.
ShoppingCart
The ShoppingCart object is a nonvisual object that stores items a user selects for purchase. This object is a model object because its primary purpose is to represent a set of items that the user selects for purchase. It also keeps track of the number of items selected for purchase and the total cost of the items.
CartView
The CartView object is a visual object that displays the current ShoppingCart items in the user interface. This object must get the current data from the ShoppingCart object and display it appropriately in the user interface; this requirement is described in “Determining component
types and a messaging strategy” on page 73.
ProductThumbnail
The ProductThumbnail object is a visual object that displays a thumbnail image, name, and price for each product in the catalog object.
72 Chapter 4: Architecting Flex Applications
ThumbnailView
The ThumbnailView object is a visual object that displays a set of ProductThumbnail objects.
This object must get the product data from the catalog object and pass it into ProductThumbnail objects that represent the individual products contained in the catalog object. This requirement are described in “Determining component types and a messaging strategy” on page 73.
ProductDetail
The ProductDetail object is a visual object that displays a large image, name, price, description, and quantity selector for a selected ProductThumbnail object or a selected item in the ShoppingCart object. This object also lets the user add a selected item to the ShoppingCart object.
This object must get the index of the selected ProductThumbnail or ShoppingCart item and display the corresponding product data appropriately in the user interface; this requirement is described in “Determining component types and a messaging strategy” on page 73.
Checkout
The Checkout object is a visual object that contains a form for placing an order based on the current items in a ShoppingCart object. This object must get the current data from the ShoppingCart object and display it appropriately in the user interface; this requirement is described in “Determining component types and a messaging strategy” on page 73.

Determining component types and a messaging strategy

After you establish an object model, you need to consider what types of Flex component to use for each object in the model. For simple visual objects that use standard Flex user-interface components, you can create an MXML component. For nonvisual objects, or to modify the behavior of a visual component, you can create an ActionScript component. For complex visual objects, you can create a SWC component in Macromedia Flash MX.
For more information about MXML components, see Chapter 15, “Building an Application with Multiple MXML Files,” in Developing Flex Applications. For more information about ActionScript components, see Chapter 18, “Creating ActionScript Components,” in Developing Flex Applications. For more information about SWC components, see Developing Flex Applications.
When you have a plan for the types of Flex components to use in your object model, you must start thinking about a messaging strategy for acquiring and manipulating application-specific data. You need a way for the objects in the application to send and receive data. To solve this problem in the Flex Store application, many of the objects contain data object properties, which are ActionScript properties or
<mx:Model> tags that you use to pass data into the objects.
This following sections describe the component types and messaging strategy of the Flex Store application.
Architecting an application 73
Flex Store component figure
The following figure shows the component type of each object in the object model of the Flex Store application. The Data Object boxes show which objects contain data object properties.
FlexStore
(MXML Application
ShoppingCart
(ActionScript component)
Model
object)
View
catalog
<mx:Model> tag
Model
CartView
(MXML component)
View
cartData
variable of type
ShoppingCart
Data Object
ProductThumbnail
(MXML component)
View
dataObject
variable
Data Object
Thumbnail
(MXML component)
View
dataObject
variable
Data Object
ProductDetail
(MXML component)
View
dataObject
variable
Data Object
ShoppingCart
(MXML component)
View
cartData
variable of type
ShoppingCart
Data Object
FlexStore
The FlexStore object, the top-level application object, is an MXML file. It contains standard MXML tags that declare most of the application, and custom MXML tags that declare custom objects. For the custom tags, this file declares them to use the default namespace.
The FlexStore object also contains some application-level ActionScript code that helps glue the application together, and Cascading Style Sheet (CSS) definitions. The ActionScript code and CSS definitions are contained in external files to promote modularity and reusability.
catalog
The catalog object is declared in an <mx:Model> tag in the FlexStore.mxml file because it is a simple object with the sole function of data storage, and it requires no data typing. Compare this with the ShoppingCart object, which is also in the model tier, but stores and manipulates data. The data for the catalog object is defined in an external XML file, catalog.xml, which is accessed using a named web service and the following
<mx:WebService id="catalogWS" serviceName="FlexStoreCatalogWS">
<mx:operation
name="getList" result="selectedItem=catalogWS.getList.result[0]"
/>
</mx:WebService>
<mx:WebService> data service tag:
Data could just as easily be accessed using an HTTP service or a server-side Java object that retrieves data from a remote data source.
74 Chapter 4: Architecting Flex Applications
The following example shows the catalog object declared in the FlexStore.mxml file:
<mx:Model id="catalog">
{catalogWS.getList.result}
</mx:Model>
The following example shows a product definition in the catalog.xml file:
<catalog>
<name>USB Watch</name> <description>So, you need to tell the time of course, but you also need a way to carry your valuable data with you at all times (you know - your MP3 files, favorite images, your ThinkGeek shopping list). This watch can handle the mission for you and do it in style. It can store up to 256 MB of data.</ description> <price>129.99</price> <image>assets/products/usbwatch.jpg</image> <thumbnail>assets/products/usbwatch_sm.jpg</thumbnail> ...
</catalog>
ShoppingCart
The ShoppingCart object is defined in an ActionScript class because it performs data storage and data manipulation. An ActionScript class is the appropriate component type because it can contain both properties and methods.
The ShoppingCart class contains the following properties:
var items
var total
The class contains the following methods:
addItem()
getItemCount()
getTotal()
removeItemAt()
The component is declared in the FlexStore.mxml file using a
CartView
The CartView object is defined in an MXML component because it is a visual object that you can create using MXML tags and a small amount of ActionScript code. The top-level tag of the CartView component is a Panel container.
The CartView component uses a
<mx:Script> tag to include the ActionScript file
CartView_script.as. That file contains the following property definitions:
<ShoppingCart> tag.
var selectedItem
var dataObject
The
dataObject property stores ShoppingCart data.
Architecting an application 75
The CartView_script.as file also contains the following method definitions:
dataGridChange(selectedItem)
removeItem()
The CartView.mxml component contains an items along with several other user-interface components and an
<mx:DataGrid> tag for displaying ShoppingCart
<mx:NumberFormatter> tag for
displaying prices in a specific format. The component is declared in the ShoppingCart.mxml file using a
<CartView> tag.
The following example shows how the value of the
dataObject property is set to the cart
ShoppingCart object by using curly braces ({ }) to bind data:
... <ShoppingCart id="cart"/> ... <CartView id="cartView" dataObject="{cart}"
width="370" height="{549-productDetail.height}" itemSelected="selectedItem=event.target.selectedItem" checkOut="changeView('checkout')" vScrollPolicy="off"/>
ProductThumbnail
The ProductThumbnail object defines a custom cell renderer used by the ThumbnailView object. You use a cell renderer to manipulate and display custom cell content for each of row of a list­based component. In this example, you use ProductThumbnail to define an image and two labels in each cell of a TileList control.
The ProductThumbnail component contains the following properties defined in an
<mx:Script> tag:
var _filteredOut
var dataObject
The
_filteredOut property indicates whether to dim a ProductThumbnail’s appearance based
on the currently selected price range. The
The component contains the following methods defined in an
dataObject property stores catalog data.
<mx:Script> tag:
setValue()
set filteredOut()
hideWhenChanging()
The following example from the ThumbnailView.mxml file shows how the is set to the catalog data for the the ProductThumbnail object:
... <mx:Script>
<![CDATA[
var dataObject; var selectedItem;
]]>
</mx:Script>
76 Chapter 4: Architecting Flex Applications
currentItem in the catalog object, and the cell renderer is set to
dataObject property
... <mx:TileList id="myTile" dataProvider="{dataObject}"
cellRenderer="ProductThumbnail" width="100%" height="100%" itemWidth="120" itemHeight="116" borderStyle="none" dragEnabled="true" change="selectedItem=dataObject[myTile.selectedIndex];
dispatchEvent({type:'change'})
"/>
The component is declared in the ThumbnailView.mxml file using a <ProductThumbnail> tag.
ThumbnailView
The ThumbnailView object is defined in an MXML component because it is a visual object that you can create using MXML tags and a small amount of ActionScript code. The top-level tag of the ThumbnailView component is a VBox container.
The component is declared in the FlexStore.mxml file using a
<ThumbnailView> tag.
The component contains the following properties defined in an
<mx:Script> tag:
var selectedItem
var dataObject
var min
var max
The dataObject property stores catalog data.
The component contains the following methods defined in an
<mx:Script> tag:
filter()
sort()
unselect()
The component contains an <mx:TileList> tag for displaying a set of ProductThumbnail components in a grid format.
The following example from the FlexStore.mxml file shows how the to the
catalog.product property. Notice that you reference the custom ThumbNailView object
using the default namespace.
<ThumbnailView id="thumbView"
label="Product Catalog" dataObject="{catalog}" change="selectedItem=event.target.selectedItem"
/>
ProductDetail
The ProductDetail object is defined in an MXML component because it is a visual object that you can create using MXML tags and a small amount of ActionScript code. The top-level tag of the ProductDetail component is a VBox container.
dataObject property is set
Architecting an application 77
The component contains the following property definitions in an <mx:Script> tag:
var shoppingCart
var dataObject
The shoppingCart property stores ShoppingCart data.
The component contains MXML tags for displaying product details. It also contains an
<mx:NumericStepper> tag for selecting product quantity, and an <mx:Button> tag for adding
items to the ShoppingCart.
The following example from the FlexStore.mxml file shows how the set to the
cart ShoppingCart object. Notice that you reference the custom ShoppingCart and
ProductDetail objects using the default namespace.
... <ShoppingCart id="cart"/> ... <ProductDetail id="productDetail" dataObject="{selectedItem}"
shoppingCart="{cart}" width="370" height="330" vScrollPolicy="off"/>
...
Checkout
The Checkout object is defined in an MXML component because it is a visual object that you can create using MXML tags and a small amount of ActionScript code. The top-level tag of the Checkout component is a VBox container.
shoppingCart property is
The component uses an
<mx:Script> tag to include the ActionScript file Checkout_script.as.
The Checkout_script.as file contains the following property definitions:
var cartData
var months
var years
var shippingCost
The
cartData property stores ShoppingCart data.
The component uses the
The Checkout_script.as file contains the following method definition:
confirmOrder()
The Checkout component contains an <mx:Form> tag for entering order information, and an
<mx:Model id="order"> tag for storing order information. It also contains data formatter tags
and data validator tags.
The following example from the FlexStore.mxml file shows how the set to the
cart ShoppingCart object. Notice that you reference the custom ShoppingCart and
Checkout objects using the default namespace.
... <ShoppingCart id="cart"/> ... <Checkout id="checkoutView" cartData="{cart}"/>
months, years, and shippingCost properties to store credit card data.
shoppingCart property is
78 Chapter 4: Architecting Flex Applications

Summary of Flex application features

The following table describes the features that you are most likely to use when building Flex applications:
Feature Description
User interface controls Controls are user-interface components, such as Button, TextArea, and
ComboBox controls. You use MXML tags to add controls to an application.
For more information, see Chapter 2, “Using Controls,” in Developing Flex Applications.
User interface containers Containers are user-interface components that let you control the
layout characteristics of the user-interface components that they contain. You can use containers to control child sizing and positioning, or to control navigation among multiple child containers. You use MXML tags to add containers to an application.
For more information, see Chapter 4, “Introducing Containers,” in Developing Flex Applications.
MXML components MXML components are Flex components written in MXML files. They
provide an easy way to extend an existing Flex component and encapsulate the appearance and behavior of a component in a custom MXML tag. You use MXML tags to add MXML components to an application.
For more information, see Chapter 15, “Building an Application with Multiple MXML Files,” in Developing Flex Applications.
ActionScript components ActionScript components are Flex components written in ActionScript
classes. They are a good choice for nonvisual components. You can use MXML tags to add ActionScript components to an application.
For more information, see Chapter 18, “Creating ActionScript Components,” in Developing Flex Applications.
SWC components SWC components are created in the Flash MX authoring environment
and exported in SWC files for use in Flex applications. They are a good choice for complex visual objects. You use MXML tags to add SWC components to an application.
For more information, see Developing Flex Applications.
Data binding The data binding feature provides a simple syntax for automatically
copying the value of a property of one client-side object to a property of another object at runtime.
For more information, see Chapter 32, “Binding and Storing Data in Flex,” in Developing Flex Applications.
Data models Data models let you store application-specific data. They are used for
data validation and can contain client-side business logic. You can define data models in ActionScript classes or MXML tags.
For more information, see Chapter 32, “Binding and Storing Data in Flex,” in Developing Flex Applications.
Summary of Flex application features 79
Feature Description
Data services Data service objects let you interact with server-side data sources. You
can work with data sources that are accessible using SOAP-compliant web services, Java objects, or HTTP GET or POST requests. For more information, see Chapter 31, “Managing Data in Flex,” in Developing Flex Applications.
Data validation Data validators help you ensure that the values in the fields of a data
model meet certain criteria. For example, you can use a validator to check whether a user entered a valid ZIP code value in a TextInput control. For more information, see Chapter 33, “Validating Data in Flex,” in Developing Flex Applications.
Data formatting Data formatters let you format data into strings before displaying it in
the user interface. For example, you can use a formatter to display a phone number in a specific format. For more information, see Chapter 34, “Formatting Data,” in Developing Flex Applications.
Cursor management Cursor management lets you control the cursor image within a Flex
application. You can use cursor management to provide visual feedback to users to indicate when to wait for processing to complete, to indicate allowable actions, or to provide other types of feedback. For more information, see Chapter 24, “Using the Cursor Manager,” in Developing Flex Applications.
History management History management lets users navigate through a Flex application
using the web browser’s Back and Forward navigation commands. It also lets users return to the previous location in an application if the browser accidentally navigates away from that location.
For more information, see Chapter 26, “Using the History Manager,” in Developing Flex Applications.
Drag-and-drop management
Drag-and-drop management lets you move data from one place in a Flex application to another. This feature is especially useful in a visual application where your data can be items in a list, images, or Flex components. For more information, see Chapter 22, “Using the Drag and Drop Manager,” in Developing Flex Applications.
ToolTips ToolTips let you provide helpful information to application users. When
a user moves their mouse over a graphical component, a toolTip pops up and displays its text. For more information, see Chapter 23, “Using ToolTips,” in Developing Flex Applications.
Styles, fonts, and themes Styles, fonts, and themes help you define the overall appearance of
applications. You can use them to change the appearance of a single component, or apply them across all components. For more information, see Chapter 20, “Using Styles and Fonts,” in Developing Flex Applications.
80 Chapter 4: Architecting Flex Applications
Feature Description
Behaviors Behaviors let you add animation or sound to applications in response to
user or programmatic action. For more information, see Chapter 21, “Using Behaviors,” in Developing
Flex Applications.
Repeaters Repeaters let you dynamically repeat any number of controls or
containers specified in MXML tags, at runtime. For more information, see Chapter 8, “Dynamically Repeating Controls and Containers,” in Developing Flex Applications.
Image and media importing You can use MXML tags to import several images into applications.
Flex supports several formats, including JPEG, PNG, GIF, and SVG images and SWF files. In addition, you can use the MediaDisplay, MediaController, and MediaPlayback controls to incorporate streaming media into Flex applications. Flex supports the Flash Video File (FLV) and MP3 file formats with these controls. For more information, see Chapter 13, “Importing Images,” in Developing Flex Applications.
Deferred instantiation Deferred instantiation lets you determine when controls and other
components are created when you invoke a Flex application. For more information, see Chapter 27, “Improving Layout
Performance,” in Developing Flex Applications.
JSP tag library You can use the Flex JSP tag library to add MXML code to your JSPs
or create custom HTML wrappers for your Flex applications. For more information, see Chapter 38, “Using the Flex JSP Tag Library,” in Developing Flex Applications.
ActionScript scripting ActionScript lets you perform actions with the components that are
represented by MXML tags. You use ActionScript in your Flex applications to do the following:
Handle events
Define custom functions and methods
Call ActionScript functions
Work with components after they are instantiated
For more information, see Chapter 16, “Working with ActionScript in Flex,” in Developing Flex Applications.
Debugging Flex includes support for debugging and warning messages, an error-
reporting mechanism, and a command-line ActionScript debugger to assist you in debugging your application. For more information, see Chapter 36, “Debugging Flex Applications,” in Developing Flex Applications.
Summary of Flex application features 81
Feature Description
ActionScript profiling The ActionScript Profiler helps you identify performance problems in
applications. It can show you where too many calls to a particular method might be occurring or where an object’s instantiation might be taking too long. For more information, see Chapter 37, “Profiling ActionScript,” in Developing Flex Applications.
Administration Flex includes several configuration files to administer the behavior of
your applications. Settings specific to the Flex application are defined in the flex_app_root/WEB-INF/flex/flex-config.xml file. Web application settings are located in the flex_app_root/WEB-INF/web.xml file.
You can use the mxmlc tool included with Flex to compile your MXML files into SWF files without requesting them from a browser or Flash Player. To use mxmlc, you must have a Java runtime environment (JRE) in your system path.
For more information, see Chapter 39, “Administering Flex,” in Developing Flex Applications.
82 Chapter 4: Architecting Flex Applications

INDEX

A
ActionScript
about 43 class import 51 classpath 52 compared to ECMAScript 44 compared to JavaScript 44 compiling 45 creating components 53 custom components 53 defining components 53 examples 54 identifiers 47 importing classes 51 importing files 48 in MXML 44, 47 including and importing 48 including files 48 package import 51 packages 45 script blocks 48 Script tag 48 special characters 46
using 17, 46 ActionScript Profiler 61 Application container, about 25 applications
appearance 67
architecture of 70
developing 57 ASP, and Flex coding 58
B
behaviors
about 67
performance tuning 69
C
CartView object 72, 75 Cascading Style Sheets (CSS) 32 catalog object 72, 74 characters, special 46 Checkout object 78 classes classpath 52 classpath, in ActionScript and SWC files 52 ColdFusion, moving to Flex 59 command-line debugger 61 compc 61 compiler setting 52 compiler tags 40 compiling, ActionScript classes 52 components
about 12 creating in ActionScript 53 example 12 in MXML 36 setting properties of 36 sizing 67
containers
about 12 example 12 nesting 68
performance tips 68 controls 12 CSS, and MXML 32 custom components
about 33, 53
example 53
in ActionScript 53
in MXML 33
types 54
83
D
data binding
about 13
MXML syntax 28 data formatters 31 data models
about 13
in MXML 30
using 12 data services
and MXML components 64
in MXML 29 development environment, Flex 60
E
ECMAScript 44 effects
about 33
changing components 33
performance tuning 69
using 33 event handlers
definition 27
error handling 66
in MXML 27
using 27, 66 event model, standards in MXML 42
F
faceless components, definition 54 features, summary 79 file naming, MXML 36 Flash Debug Player
about 10
performance 70
using 10 Flash Player 10 Flash, moving to Flex 59 Flex
about 7
ActionScript and 17
application examples 11
application framework 15
application model 12
benefits 9
class library 15
components 12
containers 12
controls 12
data binding 13 data models 13 development environment 60 development process 14 development tools 60 features 19 Flash Debug Player and 10 Flash Player and 10 J2EE servers and 9 MVC architecture 13 MXML 16 n-tier model and 8 profiling 10 programming model 15 runtime services 15 standards supported 10 URL to 14
Flex applications
appearance 67 architecting 57 behaviors 67 coding process 58 data services 64 event handlers 65 example 70 laying out interface 63 organizing data 63 performance tuning 67 separating data model from view 64 sizing components 67 skins 67
styles 67 Flex development environment 60 Flex development tools
about 60
ActionScript Profiler 61
command-line debugger 61
compc 61
Flash Debug Player 61
mxmlc 61 Flex Store
application 71
component diagram 74
object model diagram 72 FlexStore object 72, 74
84 Index
G
graphics, standards in MXML 42
H
HTML, moving to Flex 58 HTTP services, standards in MXML 42
I
id property 47 identifiers 40 include directive 50 including ActionScript 48
J
J2EE servers 9 Java, standards in MXML 42 JavaScript, compared to ECMAScript 43
L
languages
ActionScript 43
MXML 23 layout containers, performance tuning 68 local namespaces 34
M
model-view-controller architecture 71 MVC architecture
about 71
Flex and 13 MXML
about 23
ActionScript and 44, 47
ActionScript classes and 15
controlling user interaction 26
CSS and 32
data binding 28
data formatting 31
data models 30
data services 29
effects 33
event handlers 27
example 24
Hello World example 24
moving from Flash 23
Script tag 48
separating from ActionScript 54
simple applications 24
standards and 41
style property of tag 39 syntax 35 tag syntax 41 tags 36 URLs 24 using 16 using ActionScript with 27 XML data 39 XML namespaces 34
MXML components
about 33 data service components 64
MXML syntax
about 35 array properties 37 compiler tags 40 CSS 32 data binding 28 data formatters 31 data models 30 data services 29 effects 33 file naming 36 identifiers 40 objects 37 requirements 41 scalar properties 36 Script tag 48 setting component properties 36 styles 39 tags 36, 41 XML properties 39
mxmlc 61
N
namespaces 34
O
object model, developing 71
P
performance tuning
containers 68 effects 69 Flash Debug Player 70 initial layout 68 runtime 68
Index 85
Product Thumbnail object 72, 73 ProductDetail object 77 ProductThumbnail object 76 properties, setting in MXML 36
Q
query parameters 62
R
relative paths 51
S
Script tag
about 47
class import 51
external file reference 51
in MXML 48
include directive 50
including ActionScript files 48
package import 51
source attribute of 49
using 49
with ActionScript 48 ShoppingCart object 72, 75 skins 67 standards, in MXML 41 styles
about 67
in MXML 39 SWC files, classpath 52
Z
zooming, applications 67
T
tags
compiler 40
in MXML 36 ThumbnailView object 73, 77 tools, development 60
U
user interface tags 26 user_classes, directory 52
W
web services, standards in MXML 42
X
XML data 39 XML, namespaces 34
86 Index
Loading...