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
Loading...
+ 60 hidden pages