BUY THIS BOOK
Add to Cart

Print Book $54.99


Add to Cart

Print+PDF $71.49

Add to Cart

PDF $43.99

Safari Books Online

What is this?

Add to UK Cart

Print Book £38.99

What is this?

Looking to Reprint or License this content?


Programming Flex 2
Programming Flex 2 The Comprehensive Guide to Creating Rich Internet Applications with Adobe Flex By Chafic Kazoun, Joey Lott
April 2007
Pages: 502

Cover | Table of Contents


Table of Contents

Chapter 1: Introducing Flex
Flex is a collection of technologies that enables you to rapidly build applications deployed to Flash Player, a runtime environment for delivering sophisticated user interfaces and interactivity. Flex leverages existing, matured technologies and standards such as XML, web services, HTTP, Flash Player, and ActionScript. Even though Flex allows you to create complete rich Internet applications, it does so in a relatively simple and intuitive manner. While Flex does allow you to get under the hood for more granular control over all the elements, it significantly lowers the learning curve in that it allows you to compose applications rapidly by assembling off-the-shelf components, including UI controls, layout containers, data models, and data communication components.
In this chapter, we'll introduce Flex and Flex technologies in more detail so that you can better understand what Flex is and how you can best get started working with it. You'll learn what elements a Flex application uses and how they work together. We'll also compare and contrast Flex with other technologies for creating both standard and rich Internet applications.
If you're new to Flex, you may not yet have a clear understanding of what a Flex application is, how it works, and what benefits it has over alternative technologies and platforms. You build Flex applications utilizing the Flex framework, and you deploy them using Flash Player. In the following sections, you'll learn more about Flash Player, the Flex framework, and additional technologies that may be part of a Flex application.
Flex is part of the Adobe Flash Platform, which is a set of technologies with Flash Player at the core. Flex applications are intended to be deployed to Flash Player, meaning Flash Player runs all Flex applications. With nearly every computer connected to the Internet having some version of Flash Player installed, and an increasing number of mobile devices being Flash-enabled, Flash Player is one of the most ubiquitous pieces of software anywhere. Adobe estimates that each new version of Flash Player has adoption rates reaching 80% in less than 12 months (Flash Player 8 reached 86% within 9 months). The reasons for such quick adoption rates are debatable, but there are a few factors that are almost certainly causative:
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Understanding Flex Application Technologies
If you're new to Flex, you may not yet have a clear understanding of what a Flex application is, how it works, and what benefits it has over alternative technologies and platforms. You build Flex applications utilizing the Flex framework, and you deploy them using Flash Player. In the following sections, you'll learn more about Flash Player, the Flex framework, and additional technologies that may be part of a Flex application.
Flex is part of the Adobe Flash Platform, which is a set of technologies with Flash Player at the core. Flex applications are intended to be deployed to Flash Player, meaning Flash Player runs all Flex applications. With nearly every computer connected to the Internet having some version of Flash Player installed, and an increasing number of mobile devices being Flash-enabled, Flash Player is one of the most ubiquitous pieces of software anywhere. Adobe estimates that each new version of Flash Player has adoption rates reaching 80% in less than 12 months (Flash Player 8 reached 86% within 9 months). The reasons for such quick adoption rates are debatable, but there are a few factors that are almost certainly causative:
  • Flash Player content is potentially more compelling and engaging than static HTML content.
  • Flash Player is capable of providing integrated solutions that utilize data services, interactive UI design, media elements such as audio and video, and even real-time communications.
  • Well-made Flash Player content can provide a refreshing user experience that utilizes metaphors from desktop computing, such as drag-and-drop and double-click. Flash Player frees the UI design from scrolling pages of text and images.
  • Flash Player is a relatively small (one-time) download. Even with the multitude of new features added with every release, the Flash Player download is less than 1 MB. And with built-in features such as Express Install, upgrading Flash Player versions is very simple.
  • Stability and security are important considerations. Flash Player is a stable program that has been around for nearly a decade. Adobe is very careful with Flash Player security as well. Flash Player has very little access to the client's local system. It cannot save arbitrary files to the local system, and it cannot access Internet resources unless they meet very strict requirements.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Using Flex Elements
The Flex framework includes a core set of languages and libraries that are the basis of any Flex application. Using MXML, ActionScript, and the Flex class library you can construct and compile .swf content that you can then deploy to Flash Player.
MXML is an XML-based markup language that primarily describes screen layout. In that respect it is much like HTML. Using MXML tags, you can add components such as form controls and media playback components to layout containers such as grids.
In addition to screen layout, you can use MXML to describe effects, transitions, data models, and data binding. MXML is robust enough that it is possible to build many applications entirely with MXML. Flex Builder enables you to construct MXML with a WYSIWYG approach, which allows you to build basic Flex applications without writing any code.
While the WYSIWYG approach is helpful for basic prototypes and simple applications, writing MXML code is still necessary for more complex tasks. Additionally, sophisticated Flex applications generally require both MXML and ActionScript.
MXML is a declarative way to create Flex content, but the simplicity should not fool you into thinking that MXML is not powerful. MXML provides a fast and powerful way to create layout and UI content. However, MXML documents get compiled in several steps, the first of which converts the MXML to an ActionScript class. This means that MXML documents provide you with all the power of object-oriented design, but with the convenience of a markup language. Furthermore, MXML documents are treated as ActionScript classes at runtime.
ActionScript is the programming language understood by Flash Player and is the fundamental engine of all Flex applications. MXML simplifies screen layout and many basic tasks, but all of what MXML does is made possible by ActionScript, and ActionScript can do many things that MXML cannot do. For example, you need ActionScript to respond to events such as mouse clicks.
Although it is possible to build an application entirely with MXML or entirely with ActionScript, it is more common and more sensible to build applications with the appropriate balance of both MXML and ActionScript. Each offers benefits, and they work well together. MXML is best suited for screen layout and basic data features. ActionScript is best suited for user interaction, complex data functionality, and any custom functionality not included in the Flex class library.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Working with Data Services (Loading Data at Runtime)
Flex applications are generally distributed applications. That means that several computers work in conjunction to create one system. For example, all Flex applications have a client tier (discussed shortly) that runs on the user's computer in the form of a .swf running in Flash Player. In most cases, the client tier communicates with a server or servers in order to send and retrieve data. The servers provide what are called data services, which are essentially programs that have public interfaces (APIs) whereby a client can make a request to a method of that program. When a client makes such a request, it is called a remote procedure call, or RPC.
There are many types of data services. In its simplest form a data service could consist of a static text file or XML document served from a web server. A slightly more sophisticated data service might be a dynamic XML document generated via a server-side script or program, such as a PHP or ASPX page. Many data services require greater sophistication. One of the most common types of such a sophisticated data service is the web service. Web services use XML (generally in the form of SOAP) as a messaging format, and they enable RPCs using the HTTP protocol for requests and responses. Although a SOAP web service is an example of a standards-based data service, many types of data services don't necessarily conform to a particular standard set by the W3C. Many programs on the Web, for example, expose primitive data services that use arbitrary messaging formats and protocols. One such program is used by MapQuest, a popular mapping web site. For instance, you would use the following URL to view a MapQuest page with a map of Los Angeles:
Notice that the query string uses arbitrary parameters to determine what to map. Therefore, if you wanted to display a map of New York, you would change the city and state parameter values in the URL as follows:
Flash Player is capable of making RPCs to many types of data services. For example, Flash Player can make requests to any web resource using HTTP, which means it can make requests to many primitive data services such as a static or a dynamic XML document, or the MapQuest example mentioned previously. That also means it can make requests to web services. Moreover, the Flex class library simplifies requests to most data services.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Understanding the Differences Between Traditional (HTML) and Flex Web Applications
Many applications deployed on the Web use an HTML user interface. Flex applications are similar in many respects, but they have distinct differences. If you're used to building applications that use an HTML UI, it's important to take a few moments to shift how you approach building applications when you start working with Flex. What works for HTML-based applications may or may not work for Flex applications.
Both traditional and Flex applications are generally n-tiered. The exact number and types of tiers an application has depend on many factors. Most traditional applications have, at a minimum, a data tier, a business tier, and a presentation tier. Flex applications have a data tier and a business tier; however, as noted earlier, they also introduce a client tier, which is what strongly differentiates them from traditional web applications. The client tier of Flex applications enables clients to offload computation from the server, freeing up network latency and making for responsive and highly interactive user interfaces.
Data tiers generally consist of databases or similar resources. Business tiers consist of the core application business logic. As an example, a business tier may accept requests from a client or presentation tier, query the data tier, and return the requested data.
In traditional applications the presentation tier consists of HTML, CSS, JavaScript, JSP, ASP, PHP, or similar documents. Typically a request is made from the user's web browser for a specific presentation tier resource, and the web server runs any necessary interpreters to convert the resource to HTML and JavaScript, which is then returned to the web browser running on the client computer. Technically the HTML rendered in the browser is a client tier in a traditional web application. However, since the client tier of a traditional web application is stateless and fairly nonresponsive, it is generally not considered a full-fledged tier. (The exception to that generalization is the case of Ajax applications, which use client-side JavaScript and XML to build responsive and sophisticated client tiers.)
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Understanding How Flex Applications Work
Flex applications deployed on the Web work differently than HTML-based applications. It's important to understand how Flex applications work in order to build them most effectively. When you understand how Flex applications work, you can know what elements are necessary for an application and how to build the application for the best user experience. summarizes the basic concepts discussed in this section.
Figure 1-1: Understanding Flex application source-compile-deploy workflow
Every Flex application deployed on the Web utilizes Flash Player as the deployment platform. That means that a fundamental understanding of Flash Player is essential to understanding Flex. Additionally, all Flex applications use the Flex framework at a minimum to compile the application. As such, it's important to understand the relationship between the source code files, the compiler, and Flash Player.
All Flex applications require at least one MXML file or ActionScript class file, and most Flex applications utilize both MXML and ActionScript files. The MXML and ActionScript class files comprise the source code files for the application. Flash Player does not know how to interpret MXML or uncompiled ActionScript class files. Instead, it is necessary to compile the source code files to the .swf format, which Flash Player can interpret. A typical Flex application compiles to just one .swf file. You then deploy that one .swf to the server, and when requested, it plays back in Flash Player. That means that unlike HTML-based applications, the source code files remain on the development machine, and you do not deploy them to the production server.
Asset files such as MP3s, CSS documents, and PNGs can be embedded within a .swf, or they can be loaded at runtime. When an asset is embedded within a .swf, it is not necessary to deploy the file to the production server, because it is compiled within the .swf file. However, since embedding assets within the .swf often makes for a less streamlined downloading experience and a less dynamic application, it is far more common to load such assets at runtime. That means that the asset files are not compiled into the
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Understanding Flex and Flash Authoring
Many developers first learning about Flex 2 may still be unclear as to the relationship between Flex and Flash authoring, the traditional tool for creating content for Flash Player. First, you do not have to understand Flash authoring in order to work with Flex. In fact, you can get started with Flex without any prior knowledge of or experience in Flash authoring.
Flash authoring is a product that was first created in 1996 as a vector animation tool primarily aimed at creating animation content for the Web. In the many versions since that time, both Flash authoring and Flash Player (the deployment platform for Flash authoring content) have enabled greater and greater capabilities, and developers began to create rich Internet applications with the tools. However, while Flash authoring is a fantastic tool for creating animations, it is not the ideal tool for creating applications. The metaphors that Flash authoring uses at its core (such as timelines) are simply not applicable to application development.
Flex 2 is a product aimed primarily at creating applications. The framework includes a rich set of layout and user interface components, and the technology uses metaphors such as states and transitions that are appropriate to application development.
Both Flex and Flash authoring allow you to create .swf content that runs in Flash Player. In theory you can achieve the same things using both products. However, Flash is a tool that allows you to create timeline-based animations and to use drawing tools best suited for expressiveness, while Flex allows you to much more rapidly assemble screens of content with transitions and data communication behaviors. As with any craft, it is advisable to use the best tool for the job. Up until now, Flash authoring was one of the only tools for creating .swf content. But with Flex 2, we now have a tool with a more specific focus.
Although many people may initially try to frame the Flex and Flash authoring debate as a winner-takes-all scenario, it is rather naive to think of them as competing technologies. Rather, they are two complementary technologies that allow all Flash platform developers to utilize specialized tools when creating rich Internet content. In fact, Flex and Flash authoring can work very well together. As you'll see in this book, Flex can import content created in Flash authoring, allowing you to create rich Internet applications that use timeline-based content.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Understanding Flex 1.5 and Flex 2
If you are familiar with earlier versions of Flex (Flex 1 and Flex 1.5), you may be interested in the relationship between Flex 2 and those earlier versions. While Flex 2 continues to utilize MXML and ActionScript (both supported in earlier versions of Flex), it is vastly different from Flex 1 and Flex 1.5 in other respects. Flex 2 allows you to compile and deploy independent .swf files without any sort of expensive server-side services as was required by Flex 1 and 1.5 (though the ability to compile .swf files on the server at request time is still available in Flex Data Services). Flex 2 requires Flash Player 9, which allows for (and requires) the use of ActionScript 3. This latest ActionScript version introduces significant changes to the Flash Player API that offers a much improved way to add and remove display objects (including components) to the view.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Summary
In this chapter, we introduced the basics of what Flex is and what technologies and products are used to create Flex applications. You learned that Flex 2 consists of a framework (a class library) and a compiler that allow you to rapidly create Flex applications. These applications are .swf files, which you can then run in Flash Player 9.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 2: Building Applications with the Flex Framework
The majority of this book is dedicated to programming Flex applications, with detailed discussions of working with MXML and ActionScript. However, in order to meaningfully use most of what we discuss in the chapters that follow, you'll need to know how to create a Flex project, how to compile the project, and how to deploy that project so that you can view it.
In this chapter we'll discuss important topics such as the tools required for creating Flex applications and how to create new projects for Flex applications. We'll look at the elements comprising a Flex project and discuss compiling and deploying Flex applications.
In order to work with Flex and build Flex applications, you'll need tools. At a minimum you must have a compiler capable of converting all your source files and assets into the formats necessary to deploy the application. That means you need to be able to compile MXML and ActionScript files into a .swf file.
There are two primary tools you can use that include the necessary compilers:
  • The Flex SDK (Software Development Kit)
  • Flex Builder 2
The Flex SDK is a free product that includes the entire Flex framework as well as the mxmlc and compc compilers (see the section "" later in this chapter, for more details on the compilers). You can download the SDK at http://www.adobe.com/products/flex/sdk.
Flex Builder 2 is a commercial product designed to work with Flex, and it too includes the mxmlx and compc compilers. You can download a trial version of Flex Builder 2 or purchase a license at http://www.adobe.com/go/flexbuilder.
Flex Builder includes the entire SDK.
You can work with Flex Builder 2 in two ways: standalone and as a plug-in for Eclipse (http://www.eclipse.org). The standalone version of Flex Builder 2 is built on Eclipse, so it and the plug-in version are essentially equivalent. The primary differences are:
  • Flex Builder 2 standalone does not require that you already have Eclipse installed, making it an optimal solution for those who have no other use for Eclipse. On the other hand, if you already use Eclipse, or if you intend to use Eclipse for other purposes, the standalone version would essentially require you to have two installations of Eclipse—one running Flex Builder and one standard installation. If you use or plan to use Eclipse for other reasons you should definitely install the plug-in version of Flex Builder 2.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Using Flex Tool Sets
In order to work with Flex and build Flex applications, you'll need tools. At a minimum you must have a compiler capable of converting all your source files and assets into the formats necessary to deploy the application. That means you need to be able to compile MXML and ActionScript files into a .swf file.
There are two primary tools you can use that include the necessary compilers:
  • The Flex SDK (Software Development Kit)
  • Flex Builder 2
The Flex SDK is a free product that includes the entire Flex framework as well as the mxmlc and compc compilers (see the section "" later in this chapter, for more details on the compilers). You can download the SDK at http://www.adobe.com/products/flex/sdk.
Flex Builder 2 is a commercial product designed to work with Flex, and it too includes the mxmlx and compc compilers. You can download a trial version of Flex Builder 2 or purchase a license at http://www.adobe.com/go/flexbuilder.
Flex Builder includes the entire SDK.
You can work with Flex Builder 2 in two ways: standalone and as a plug-in for Eclipse (http://www.eclipse.org). The standalone version of Flex Builder 2 is built on Eclipse, so it and the plug-in version are essentially equivalent. The primary differences are:
  • Flex Builder 2 standalone does not require that you already have Eclipse installed, making it an optimal solution for those who have no other use for Eclipse. On the other hand, if you already use Eclipse, or if you intend to use Eclipse for other purposes, the standalone version would essentially require you to have two installations of Eclipse—one running Flex Builder and one standard installation. If you use or plan to use Eclipse for other reasons you should definitely install the plug-in version of Flex Builder 2.
  • The standalone version disables Java Development Tools (JDT), a plug-in used by some standard Eclipse features such as Ant (http://ant.apache.org). If you want to use JDT, you should install the plug-in version of Flex Builder 2.
    Since Flex Builder is built on Eclipse, you can use any third-party Eclipse plug-ins with the standalone version of Flex Builder.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Creating Projects
A Flex application consists of potentially many files. Although it's possible that a Flex project could consist of as little as one source file, most use tens if not hundreds of files. A typical Flex project might utilize the following:
MXML files
These files contain the majority of the application view—the layout and UI components. You can read an introduction to MXML in . You can also learn about application and MXML components (both written in MXML) in .
ActionScript classes
These files contain the source code for all the custom components, data models, client-side business logic, and server proxies. You'll find an introduction to ActionScript in .
XML files
Although XML is frequently loaded from a server as a dynamic response to an HTTP request from Flash Player, many applications also utilize static XML files as configuration parameters.
Image files
Flex applications can embed image files or load them at runtime. Working with images is covered in .
Audio and video files
Flex applications can load audio and video content for playback within the application. Audio and video are almost always loaded at runtime. Audio and video are also discussed in .
Runtime shared libraries
Runtime shared libraries are .swf files that contain code libraries that are shared between two or more Flex applications deployed on the same domain. In order to utilize a runtime shared library, you need two files: a .swf and a .swc. The .swf file contains the libraries, and the .swc file is used by the compiler to determine which libraries to exclude from the application .swf. Runtime shared libraries are discussed in more detail later in this chapter, in the section titled "."
HTML wrapper file
Flex applications are typically deployed on the Web. The published application is a .swf file. The most common way to playback a .swf on the Web is to embed it in an HTML page. The HTML wrapper file is the file that embeds the .swf.
How you configure a new Flex project depends in large part on what tool set you are using. If you're using the Flex SDK, that tool set generally requires the most work in order to configure a new project.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Building Applications
Once you've created a project and written some code, you'll want to build the project, which means compiling it and deploying it. How you accomplish these tasks depends, in part, on what tools you're using. The following subsections discuss how to compile using the mxmlc compiler. If you're using Flex Builder 2, you may want to skip directly to the section "" later in this chapter.
The mxmlc compiler is used to compile Flex applications (versus compc, which is used to compile components and libraries). When you use Flex Builder to compile, it automatically calls mxmlc (Flex Builder includes the SDK).
There are several ways you can use mxmlc, including from the command line, from a .bat or shell script, from an IDE, and from Apache Ant. Initially we'll look at using mxmlc from the command line since it's the most basic way to use the compiler (though we'll also look at using the compiler via Apache Ant later in this chapter). All the compiler flags we'll look at from the command line also apply to any other use of the compiler.
When you want to work with mxmlc from the command line, it's generally a good idea to make sure you add it to your system path. If you're running Windows and you're uncertain how to edit your system path, follow these steps:
  1. Right-click on My Computer from the desktop or from the Start menu, and select Properties.
  2. Click on the Advanced tab, and then click the Environment Variables button.
  3. In the System Variables list in the bottom part of the dialog, scroll until you see a variable called Path. Then edit the variable either by double-clicking on it or by selecting it and then clicking the Edit button.
  4. At the end of the existing value, add the path to the Flex SDK's bin directory. If you're using Flex Builder, the default location is C:\Program Files\Adobe\Flex Builder 2\Flex SDK 2\bin. If you're using the SDK and you installed the SDK in C:\FlexSDK, the location is C:\FlexSDK\bin. Windows uses a semicolon (;) as a delimiter. If necessary, add a semicolon between the existing value and the new addition.
  5. Click OK on each open dialog.
For OS X and Linux you'll want to set the
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Deploying Applications
Once you've compiled a Flex application, you next need to deploy the application. Most Flex applications are deployed to the Web, and therefore that will be our primary focus in our discussion of deploying Flex applications in this chapter.
Every Flex application consists of at least one main .swf file. Therefore, at a minimum you will always need to copy at least this one file to the deployment location (typically a web server). However, in addition to the main .swf, a Flex application may consist of the following deployable elements:
  • An HTML wrapper file
  • Data services (web services, Flash Remoting services, etc.)
  • Text and XML assets loaded at runtime
  • Images loaded at runtime
  • Audio and video assets loaded at runtime
  • Additional .swf files loaded at runtime
  • Runtime shared libraries
When you deploy an application you need to make sure that you copy all the necessary files to the deployment locations.
If you are using Ant, you can easily write a build.xml file that copies the necessary files to the deployment directories. Ant natively supports filesystem tasks such as copy and move. It also supports FTP tasks for deploying applications to remote servers.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Flash Player Security
Flash Player enforces security rules for what and how applications can access data. Flex applications can access all data resources in the same domain as the .swf. For example, if the .swf is deployed to www.example.com, it can access a web service that is also deployed at www.example.com. However, access to data resources at different domains is disallowed by Flash Player unless that domain explicitly gives permission. The Flash Player security rules disallow access to data resources unless the domains match exactly, including subdomains and even if the domain names resolve to the same physical address. That means that a .swf deployed at www.example.com cannot access data from test.example.com or even example.com unless the server explicitly allows access. The way that the domain can give permission is by way of a cross-domain policy file.
A cross-domain policy file is an XML file that resides on the server that hosts the data resources. The format for a cross-domain policy file is as follows:
<?xml version="1.0"?>
<!DOCTYPE cross-domain-policy SYSTEM
          "http://www.adobe.com/xml/dtds/cross-domain-policy.dtd">
<cross-domain-policy>
   <allow-access-from domain="www.example.com" />
</cross-domain-policy>
The root <cross-domain-policy> node can contain one or more <allow-access-from> elements. The <allow-access-from> elements specify the domains that can access the resources on the server. You can use an * wildcard in place of the subdomain, which means that any subdomain can access the data resources. For example, the following policy allows access from www.example.com, beta.example.com, test.example.com, and so on:
<?xml version="1.0"?>
<!DOCTYPE cross-domain-policy SYSTEM
          "http://www.adobe.com/xml/dtds/cross-domain-policy.dtd">
<cross-domain-policy>
   <allow-access-from domain="*.example.com" />
</cross-domain-policy>
You can also use the * wildcard in place of the entire domain to allow access from all domains:
<?xml version="1.0"?>
<!DOCTYPE cross-domain-policy SYSTEM
          "http://www.adobe.com/xml/dtds/cross-domain-policy.dtd">
<cross-domain-policy>
   <allow-access-from domain="*" />
</cross-domain-policy>
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Understanding HTML Wrappers
Flex applications run in Flash Player, and therefore they don't require any additional wrappers. However, most Flex applications embed Flash Player in an HTML page for the following reasons:
  • Many Flex applications exist as part of a larger application that is based in HTML.
  • Embedding Flash Player in an HTML page enables greater interaction with the web browser.
Assuming that you want to embed your Flex application within an HTML page, there are many ways you can go about that task. The most complex approach is to write the necessary HTML and/or JavaScript code by hand. On the other end of the spectrum, you can use a template or a tool that embeds Flash Player in an HTML page. Since templates and tools capable of embedding Flash Player are so prevalent, we won't focus on writing the HTML code, though we'll review the basics.
Flash Player runs as an ActiveX control in Internet Explorer and as a plug-in on all other browsers. You can add a Flash Player ActiveX control using the <object> HTML tag, and you can add a plug-in instance using the <embed> HTML tag. The basic code to add Flash Player to a page for any browser is as follows:
<object id='application' classid='clsid:D27CDB6E-AE6D-11cf-96B8-444553540000'
codebase='http://download.macromedia.com/pub/shockwave/cabs/flash/
swflash.cab#version=9,0,0,0' height='100%' width='100%'>
  <param name='src' value='application.swf'/>
  <embed name='application' pluginspage='http://www.macromedia.com/
shockwave/download/index.cgi?P1_Prod_Version=ShockwaveFlash' src='application.swf'
height='100%'
width='100%'/>
</object>
While the preceding code will embed Flash Player playing application.swf, it is a fairly rudimentary implementation that does not take into account issues such as Flash Player detection. In order to detect that the user has the required version of Flash Player you need a more complex implementation that generally uses JavaScript. You can also utilize something called Express Install that transparently upgrades the user's Flash Player version if he already has a version of Flash Player installed that is Version 6.0.65.0 or higher.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Using SWFObject
An alternative to using the HTML templates or writing custom HTML/JavaScript to embed Flex applications is to use SWFObject. SWFObject is a JavaScript file that enables you to quickly and simply embed Flex (and/or Flash) content in a web page. SWFObject not only simplifies your work, but it also makes the pages friendly for search engines and outputs valid HTML that can be used in HTML or XHTML 1.0 pages.
To work with SWFObject, you first need to download the JavaScript file from http://blog.deconcept.com/swfobject. You can find detailed descriptions and instructions at that same page. Briefly, here's how it works.
  1. First you must deploy the swfobject.js file with your HTML page. In the HTML you must include the .js file:
    <script type="text/javascript" src="swfobject.js"></script>
  2. Then you should create a div into which you'll write the .swf content:
    <div id="flexApplication">
      This text will be replaced with the Flex application.
    </div>
  3. Now you construct a new SWFObject instance and tell it to write to the div:
    <script type="text/javascript">
       var so = new SWFObject("flexApplication.swf", "exampleApplication",
                              "600", "400", "9", "#000000");
       so.write("flexApplication");
    </script>
The parameters for the constructor are as follows: path to .swf file, identifier to use for the embedded content, width, height, minimum Flash Player version required, and background color.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Using Runtime Shared Libraries
Runtime shared libraries are a way to share assets and libraries among multiple .swf files on the same domain. This is useful when you have several .swf files that comprise an application or span several applications deployed in the same domain in which each of the .swf files utilizes many common assets and/or libraries. For example, if a.swf and b.swf both utilize the same subset of 25 classes and embedded images that add up to 100 KB, the user has to download the same 100 KB twice, once for each .swf.
The theory behind runtime shared libraries involves a concept called linking. All .swf files employ one or both forms of linking: static and dynamic. By default, all linking is static. When an asset or source file is statically linked with a .swf, that means that it is compiled into the .swf. Dynamic linking means that the asset or source file is not compiled into the .swf, but the .swf has a reference to a .swf into which it has been compiled. Through dynamic linking you can specify certain elements that should not be compiled into a .swf in order to reduce the total file size of the .swf. The .swf is then linked to another .swf where the elements have been compiled. This allows you to extract common elements from two or more .swf files and place them into another .swf to which all the .swf files are linked dynamically. This new .swf is called a runtime shared library.
We can understand the benefit of runtime shared libraries by looking at the a.swf and b.swf example in more detail. In this example, a.swf is 200 KB, and b.swf is 400 KB. Both .swf files are deployed on the same domain. The two .swf files happen to use 100 KB of common elements. That means that if a user uses both a.swf and b.swf, she downloads 600 KB, of which 100 KB is duplicate content. Using a runtime shared library, you can introduce a new .swf, library.swf, which contains the 100 KB of common content. Although there's some overhead in creating a runtime shared library for our purposes, we'll keep the numbers simple: a.swf will now be 100 KB, and b.swf will now be 300 KB. Each will be dynamically linked to
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Summary
This chapter discussed the tool sets and the techniques that you need to create, configure, compile, and deploy Flex applications. You learned how to use the command-line compilers and well as how to use build tools such as Apache Ant. You also learned about the elements of a Flex application, how to deploy those elements, and how to optimize applications by using runtime shared libraries.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 3: MXML
MXML is a declarative markup language used to create the user interface and to view portions of Flex applications. As the name implies, MXML is an XML-based language. If you're familiar with XML or even HTML, many of the basic MXML concepts we discuss in this chapter will already be familiar to you in a general sense. In this chapter, we'll look at all the basics of working with MXML, including the syntax and structure of the language, the elements that comprise MXML, creating interactivity in MXML, and how you can use MXML to build applications.
If you've ever worked with XML or HTML, the structure of MXML will be familiar to you. MXML uses tags to create components such as user interface controls (buttons, menus, etc.), and to specify how those components interact with one another and with the rest of the application, including data sources. In the following sections we'll look at how to write MXML code.
All MXML must appear within MXML documents, which are plain-text documents. You can use any text editor, XML editor, or IDE that can work with text or XML in order to write MXML, including those listed in the preceding chapter. In order to create a new MXML document, you can create a new file with the .mxml file extension. If you are using Flex Builder, you can use the program's menus to add either a new MXML application or a new MXML component. Both are MXML documents, differing only in the root element added to the document.

Section 3.1.1.1: XML encoding

Every document can and should have an XML declaration. Many IDEs and XML editors automatically add an XML declaration. Flex Builder adds an XML declaration by default using UTF-8 as the encoding. You must place the declaration as the first line of code in the MXML document, and unless you have a compelling reason to use a different encoding, you should use UTF-8 for the best compatibility:
<?xml version="1.0" encoding="utf-8"?>
Note that an XML declaration is not strictly required by the Flex compilers. However, for well-formed MXML, you should always include the XML declaration as it is recommended by the XML 1.0 specification.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Understanding MXML Syntax and Structure
If you've ever worked with XML or HTML, the structure of MXML will be familiar to you. MXML uses tags to create components such as user interface controls (buttons, menus, etc.), and to specify how those components interact with one another and with the rest of the application, including data sources. In the following sections we'll look at how to write MXML code.
All MXML must appear within MXML documents, which are plain-text documents. You can use any text editor, XML editor, or IDE that can work with text or XML in order to write MXML, including those listed in the preceding chapter. In order to create a new MXML document, you can create a new file with the .mxml file extension. If you are using Flex Builder, you can use the program's menus to add either a new MXML application or a new MXML component. Both are MXML documents, differing only in the root element added to the document.

Section 3.1.1.1: XML encoding

Every document can and should have an XML declaration. Many IDEs and XML editors automatically add an XML declaration. Flex Builder adds an XML declaration by default using UTF-8 as the encoding. You must place the declaration as the first line of code in the MXML document, and unless you have a compelling reason to use a different encoding, you should use UTF-8 for the best compatibility:
<?xml version="1.0" encoding="utf-8"?>
Note that an XML declaration is not strictly required by the Flex compilers. However, for well-formed MXML, you should always include the XML declaration as it is recommended by the XML 1.0 specification.

Section 3.1.1.2: Applications and components

All MXML documents can have just one root node. There are two types of MXML documents, and they are defined by the type of root node they have. The first type of MXML document is an application document. Application documents use Application nodes as the root node. All Flex applications must have one application document that is the only type of document you can compile into an application. The following is an example of a basic application document that Flex Builder creates by default:
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute">

</mx:Application>
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Making MXML Interactive
MXML is useful for creating user interfaces—layout and controls. However, static content is not the hallmark of rich Internet applications. Users expect to be able to interact with Flex applications. There are two basic ways to create interactivity in MXML: handling events and data binding.
Every component does certain things. For example, at a minimum, all visual components can initialize themselves and resize. Most components can do things specific to that component type. For example, a button can respond to a user click. All of these things translate into something called an event. An event is a way that a component can notify other parts of the application when some action occurs. When a component sends out this notification we say that it dispatches an event.
The Flex event model is based on the W3C specification (see http://www.w3.org/TR/DOM-Level-3-Events).
Every type of component has set events that it dispatches. For example, a button component will always dispatch a click event when the user clicks on it (assuming the button is enabled). However, just because a component dispatches an event doesn't mean that anything is receiving a notification. If you want your application to respond to an event you must tell it to handle the event.
There are several ways you can handle events. One way is to use ActionScript to register listeners. We'll talk about that solution in , when we talk about ActionScript in more detail. In this chapter, we're more interested in the MXML solutions. Within MXML, you can add inline event handler attributes within a component tag. The event handler attribute name always matches the event name. For example, to handle a click event for a button you use the click attribute within the component tag. The value that you assign to an event attribute gets interpreted as ActionScript. The following example handles a button click event and launches an alert window:
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute">
  <mx:Button id="alertButton" label="Show Alert"
             click="mx.controls.Alert.show('Example')" />
</mx:Application>
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Summary
This chapter discussed the fundamentals of the MXML language, including its purpose and syntax. We showed how to create MXML documents, add containers and UI components, and how to make the elements of an MXML document interactive.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 4: ActionScript
ActionScript is the programming language that you can use along with MXML to create sophisticated Flex applications. While MXML is an important part of a Flex application, it is mostly used for creating the user interface, and it can go only so far in creating a complete application. For data models and sophisticated client-side business logic, you'll need to use ActionScript as well.
Flex applications require ActionScript 3.0, which represents a significant maturation from earlier versions of the language. ActionScript 3.0 is compliant with the ECMA-262 specification and leverages parts of the pending ECMAScript Edition 4 specification. ActionScript 3.0 supports a wide range of features including formalized classes, interfaces, and packages, runtime exception handling, runtime data types, reflection, regular expressions, E4X (XML), and more.
ActionScript is a standards-based, object-oriented language. Since ActionScript is an object-oriented language it can be viewed as a collection of APIs generally in the form of classes. There are three tiers of ActionScript APIs:
Flash Player APIs
These APIs are part of the Flash Player itself, and they run natively in that runtime environment. Flash Player APIs consist of core classes such as String, Number, Date, and Array as well as Flash Player-specific classes such as DisplayObject, URLLoader, NetConnection, Video, and Sound.
Flex framework APIs
These are the APIs that make up the Flex framework itself. The Flex framework is written in ActionScript, so it leverages the lower-level Flash Player APIs. The Flex framework is effectively a layer on top of the Flash Player APIs. The Flex framework APIs consist of all the Flex containers (Application, VBox, etc.), controls (Button, TextInput, etc.), and other assorted data, manager, and utility classes that are discussed throughout much of this book.
Custom APIs
These APIs are for the classes you build for use in custom applications. Custom classes can use Flash Player APIs as well as the Flex framework APIs.
The APIs that comprise the Flash Player are far too large a category to attempt to discuss in this chapter, and in fact there are books spanning many hundreds of pages that still can't cover all of the Flash Player APIs. Our assumption in this book is that you are either already basically familiar with the Flash Player APIs or you are also reading a companion reference specific to Flash Player APIs. Most ActionScript 3.0 books focus primarily on the Flash Player APIs. You will most likely find that the Flex documentation API reference is quite helpful in this regard.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Using ActionScript
When you want to use ActionScript within Flex, you have four basic options for where to place the code:
  • Inline within MXML tags
  • Nested within MXML tags
  • In MXML scripts
  • Within ActionScript classes
The preceding lists the techniques for working with ActionScript code, from the simplest to the most complex form. We'll look at each of these techniques in the following sections.
Inline ActionScript appears within MXML tags. Believe it or not, you've already seen several examples of this in . Inline event handling and data binding using curly brace syntax necessarily uses basic ActionScript. The following example uses ActionScript to display an alert dialog box when the user clicks on a button:
<mx:Button id="alertButton" label="Show Alert"
           click="mx.controls.Alert.show('Example')" />
In this example, the text assigned to the click event handler attribute is ActionScript code, which calls a show( ) method of an ActionScript class called Alert.
The next example uses data binding:
<mx:VBox>
  <mx:TextInput id="input" />
  <mx:Text id="output" text="{input.text}" />
</mx:VBox>
This example uses the ActionScript expression input.text to evaluate the text property value for the input object (the text input control).
Inline data binding represents the most limited use of ActionScript, because it can evaluate only one expression. For instance, the preceding example evaluates the expression input.text. You could use a more complex expression, such as the following:
<mx:VBox>
  <mx:TextInput id="input" />
  <mx:Text id="output" text="{'User input: ' + input.text}" />
</mx:VBox>
This example concatenates the string User input: with the user input from the text input control. You can also create even more complex expressions using inline data binding.
Inline event handlers allow you to write more complex ActionScript that can consist of several statements. ActionScript statements generally end with semicolons. The following example illustrates a button with slightly more complex event handler code, consisting of two expressions:
<mx:Button id="alertButton" label="Show Alert" click="mx.controls.Alert.
show('Example');alertButton.x += 40;" />
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
MXML and ActionScript Correlations
Content preview·