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
CONTENTS INTRODUCTION: About Flex Documentation ............................ 5 Using this manual . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5 Accessing the Flex documentation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6 CHAPTER 1: Introducing Flex ......................................... 7 About Flex. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
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 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
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 development procedures.
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.
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.
Flex adds new functionality and options to the n-tier model.
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.
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.
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 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: Server 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.
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.
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 ActionScript MXML Flex Class Library Flex Runtime Services J2EE The Flex application framework consists of the MXML scripting language, the ActionScript programming language, and the Flex class library.
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.
The second line begins with the tag, the root element of a Flex application. This tag includes the Flex namespace declaration. The content between the beginning and end 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.
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 block, as the following example shows:
-
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.
-
Feature Description Details Behaviors Enhances the user experience through animation, motion, sound, and effects. 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. Event model Occurrences that require a response from a Flex application.
-
• 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.
-
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 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
-
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 tag, have a property that takes a URL of an external file as a value. For example, you can use the source property in an tag to reference an external ActionScript file instead of typing ActionScript directly in the body of the tag.
-
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.
-
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.
-
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.
-
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 tag:
-
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 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.
-
{homePhoneInput.
-
]> 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.
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.
Dogs Cats Mice 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. PAGE 35XML 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. PAGE 36Naming 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.
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.
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: If the property is explicitly typed as Object like the value property in the following example, you can specify an anonymous object using the tag.
The following example shows how you specify an anonymous object as the value of the dataProvider property: 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.
Compiler tags Compiler tags are tags that do not directly correspond to ActionScript objects or properties.
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 tag requires both source and destination properties. The tag cannot contain an id property. The tag and its subclasses require a field property. The tag cannot contain an id property.
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.
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 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
• 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.
• 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.
The following figure shows the source files used to generate a SWF file that your J2EE server sends to the client: Source Files The top-level MXML file includes blocks, imported ActionScript files, and components defined by ActionScript files or MXML files. Compiler/Linker J2EE Server Client ActionScript classes and packages referenced in the application files are included in the final SWF.
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: Referring to Flex components When you refer to Flex components in ActionScript, the component must have an id property set.
The script within a given tag is accessible from any component in the MXML file. The 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: PAGE 49Included 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.
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 directive uses the following syntax: #include "file_name" The following example includes the myfunctions.as file: Note: The #include directive is a special kind of ActionScript statement. Do not end the line with a semicolon.
Referring to external files The source attribute of the 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 tag’s attribute: source • 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.
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.
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.
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.
One MXML document (function call in MXML tag event) The logic for the function is inside an block in the MXML document, and is called from the MXML tag’s click event, as the following code shows: PAGE 56
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.
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.
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.
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.
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.
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.
The following table describes the query string parameters that you can use to get additional information: Query parameter Description ?accessible=true Adds screen reader accessibility to all components that are capable of accessibility. Available when production-mode is set to true or false. ?asprofile=true Generates ActionScript profiling information. ?debug=true Enables ActionScript debugging for an application. Overrides the debug setting for all applications set in the flex-config.xml file.
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.
Feature Description Data formatter Converts raw data to a formatted string. Formatters are triggered just before data is 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. Data binding Copies data stored in one object to another object. For example, you can bind data from the fields of a user input form to fields in a data service request.
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 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.
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).
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.
You could replace the previous layout with the following layout to achieve the same effect: label="Visa"/> label="MasterCard"/> label="Diner's Club"/> label="AmEx"/> 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 suspendBackgroundProcessing.
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.
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.
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: ShoppingCart Model FlexStore View CartView View ProductThumbnail View catalog Model ProductDetail View Thumbnail 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.
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.
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.
The following example shows the catalog object declared in the FlexStore.mxml file: {catalogWS.getList.result} The following example shows a product definition in the catalog.xml file: USB Watch 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).
The CartView_script.as file also contains the following method definitions: • • dataGridChange(selectedItem) removeItem() The CartView.mxml component contains an tag for displaying ShoppingCart items along with several other user-interface components and an tag for displaying prices in a specific format. The component is declared in the ShoppingCart.mxml file using a tag.
... The component is declared in the ThumbnailView.mxml file using a tag.
The component contains the following property definitions in an tag: • • var shoppingCart var dataObject The shoppingCart property stores ShoppingCart data. The component contains MXML tags for displaying product details. It also contains an tag for selecting product quantity, and an tag for adding items to the ShoppingCart. The following example from the FlexStore.mxml file shows how the shoppingCart property is set to the cart ShoppingCart object.
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.
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.
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.
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.
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
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 Pla
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 use
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 T tags compiler 40 in MXML 36 ThumbnailView obj