November 23, 2008

Data Binding Basics

Posted by Jeremy Mitchell
There are many reasons to choose Flex as your development platform for web-based software applications. Everyone is already familiar with Adobe's claim of a superior user experience delivered via Flex's rich client (aka fat or thick client). However, developers and project sponsors alike are drawn to features of the Flex SDK which promote rapid development of feature-rich, robust applications.

Data binding is a great example of one of these features.

Exposed through the MXML API, data bindings allow developers to "bind" the value of one object property (destination property) to the value of another object property (source property) using MXML or MXML + inline ActionScript.

<mx:Binding source="source.text" destination="destination.text" />

<mx:TextInput id="source" />
<mx:TextInput id="destination" />


<mx:TextInput id="source" />
<mx:TextInput id="destination" text="{source.text}" />
By utilizing data bindings, any change to the value of the source property is immediately reflected in the destination property. It is important to note that data bindings are "one way". Source property changes affect the destination property value but not vice versa.

One benefit of using the <mx:Binding> tag instead of inline ActionScript is the ability to bind a property to multiple source properties. If any of the source properties change so does the destination property.

<mx:Binding source="source.text" destination="destination.text"/>
<mx:Binding source="source2.text" destination="destination.text"/>

<mx:TextInput id="source"/>
<mx:TextInput id="source2"/>

<mx:TextInput id="destination"/>
However, both methods allow you to perform operations on a source property value or derive a value from the combination of multiple source properties. See Binding Expressions discussed later.

Note: a source property can only be identified for data binding if the object to which it belongs has an id property.

Although it is possible to bind the text property of one TextInput control to the text property of another TextInput control as demonstrated in the previous example, data binding is not limited to such a scenario.

Properties of visual elements may be bound to non-visual elements and vice versa. In fact, an predominant Flex architecture, MVC, relies on the ability to bind visual elements in the "view" to non-visual elements in the "model".

Also, you could bind the text property of a TextInput control to the selectedIndex property of a ComboBox control if you so choose.

Data bindings are not limited to the binding of "like" properties or "like" elements.

Note that data bindings are, however, limited to properties of identical data types or scenarios where type casting is possible. For example, you can bind a property with a data type String (i.e. text property) to a property with a data type of Int (i.e. selectedIndex) since an Int can be implicitly cast to a String. However, the reverse is not true - a property with a data type of Int cannot be bound to a property with a data type of String.

Data binding could also be accomplished by using ActionScript to add an event listener to the source object which listens for a specified event and calls a specified event handler method responsible for changing the destination object's property value to the source object's property value.

<mx:Application xmlns:mx="" creationComplete="init()">

    private function init():void {
    private function updateValue(event:KeyboardEvent):void {
      destination.text = source.text;

<mx:TextInput id="source" />
<mx:TextInput id="destination" />
MXML data binding just allows you to do it easier and with less code.

While some may refer to such capabilities as nothing more than "syntactic sugar", most developers can appreciate the convenience and accessibility demonstrated by Flex's MXML implementation of data bindings.

Keep in mind that using MXML to bind data binds the properties to one another at compile time. If you want to bind data at runtime based on a condition, you will have to use ActionScript.

Binding Expressions

A data binding is the simplest form of a binding expression.

More advanced binding expressions combine the use of data bindings with ActionScript operations. Since binding expressions define the value of an MXML attribute, they must return a value and be wrapped in curly braces. Without curly braces, your binding expression will be interpreted as a literal value.

Binding expression are most commonly used to accomplish the following:
  1. Bind the value of one object property to the property of another object (simple data binding)
  2. String concatenation that includes one or more binded properties
  3. Calculations on one or more binded properties
  4. Conditional operations on one or more binded properties
Simple data binding:

<mx:ComboBox id="c" dataProvider="{myArray}" />

<mx:ViewStack id="v" selectedIndex="{c.selectedIndex}">
    <mx:Label text="1"/>
    <mx:Label text="2"/>


<mx:ComboBox id="c" dataProvider="{myArray}" />

<mx:Binding source="c.selectedIndex" destination="v2.selectedIndex" />

<mx:ViewStack id="v2">
    <mx:Label text="1"/>
    <mx:Label text="2"/>
String concatenation:

<mx:TextInput id="fname" />
<mx:TextInput id="lname" />

<mx:Label text="{'First Name: ' + fname.text}" />
<mx:Label text="{'Full Name: ' + fname.text + ' ' + lname.text}" />


<mx:TextInput id="fname" />

<mx:Binding source="{'First Name: ' + fname.text}" destination="destination.text" />

<mx:Label id="destination"/>

<mx:NumericStepper id="quantity" />

<mx:TextInput id="price" />

<mx:Label text="{'Total: ' + quantity.value * Number(price.text)}" />


<mx:NumericStepper id="quantity" />

<mx:TextInput id="price" />

<mx:Binding source="{'Total: ' + quantity.value * Number(price.text)}" destination="destination.text" />

<mx:Label id="destination"/>

<mx:NumericStepper id="quantity" />

<mx:Label text="{(quantity.value % 2) ? 'Odd' : 'Even'}" />


<mx:NumericStepper id="quantity" />

<mx:Binding source="{(quantity.value % 2) ? 'Odd' : 'Even'}" destination="destination.text" />

<mx:Label id="destination"/>

October 23, 2008

Flex UI Controls

Posted by Jeremy Mitchell
A Flex application's user-interface (UI) is composed of two component types — containers and controls. Containers define application layout and navigation; controls represent a broad category of UI objects required of a fully functional and interactive application.

Flex user interface controls are found in the mx.controls package of the Flex Class library.

Similar to the controls found on a traditional "Control Panel" (gauges, buttons, dials, indicators, etc), most Flex UI controls provide users control of your application.

However, despite the term, some Flex controls are not interactive and provide no control whatsoever. Examples of noninteractive controls include Label and ProgressBar.

The remainder are interactive controls and as such "can participate in tabbing and other kinds of keyboard focus manipulation, accept low-level events like keyboard and mouse input, and be disabled so that it does not receive keyboard and mouse input." Interactive controls provide the level of interaction required for users to perform desired tasks or business functions.

Common control types include text-based controls, button-based controls, and data provider controls (which include both list-based controls and menu-based controls).

Text-based controls are designed to display text and/or receive text input. Examples include Label, Text, TextArea, TextInput, and RichTextEditor.

Button-based controls receive user input in the form of keyboard or mouse events. Examples include Button, LinkButton, CheckBox, RadioButton and PopUpButton.

Data provider controls display data from a variety of sources, both internal and external to your application. All data provider controls require designation of a "data provider".

List-based controls (a subset of data provider controls) visually represent hierarchical or non-hierarchical (flat) data structures. Examples include ComboBox, List, HorizontalList, DataGrid, TileList and Tree.

Menu-based controls (another subset of data provider controls) enable user-initiated navigation through use of a static menu (always visible) or a popup menu (visibility is initiated by a user or system event). Examples include Menu, MenuBar and PopUpMenuButton.

All Flex controls subclass (or extend) the UIComponent class, and therefore, inherit the following key behaviors:

- resizing capabilities
- positioning capabilities
- ability to dispatch events
- ability to accept keyboard focus and mouse input
- ability to control visibility

Like all Flex UI components, controls can be sized, positioned and styled according to your needs.

Sizing requires the use of height and width properties - either explicitly (by setting the height and width properties to numeric pixel values) or relatively (using percentage values in relation to the parent container).

In many instances the positioning of a control is determined by the layout property (horizontal or vertical) of the parent container in conjunction with the hierarchical sequence of the control. For example, if a control represents the 3rd child element of a parent container with the layout property set to horizontal, the control will be positioned 3rd from the left.

<mx:Application xmlns:mx="">

    <mx:Panel title="Panel Container with Horizontal Layout"
        paddingBottom="5" paddingLeft="5" paddingRight="5" paddingTop="5">
        <mx:Button label="One"/>
        <mx:Button label="Two"/>
        <mx:Button label="Three"/>

However, when the parent container uses absolute positioning, the X and Y properties of the control specify the horizontal and vertical pixel coordinates within the parent container. Absolute positioning enables overlap of controls if necessary.

Also, the appearance of a control can be customized through the use of styles and skins utilizing the CSS Explorer.

Fortunately, Flex ships with a number of pre-built controls ready for inclusion in your application. Most controls are accessible via MXML (or ActionScript) during the development phase of your Flex application. MXML provides a mechanism for creating (instantiating) control components (objects) and setting control properties (including registration of event handlers with control events).

At runtime, the same control properties (including event handlers) are accessible via ActionScript only. ActionScript also provides access to the methods (or functions) of a Flex control. Runtime access to Flex controls provides the dynamic capabilities required of highly interactive and responsive application.

September 19, 2008

Flex UI Containers

Posted by Jeremy Mitchell
Flex containers serve as a mechanism for defining application layout and navigation. Common layout containers include VBox, HBox, Canvas, Tile and Form. Navigation containers include Accordion, Tab Navigator and View Stack. Each container descends from the Container Class, serves a unique purpose and is available for use at the discretion of the application developer.

Layout Containers

Layout containers dictate the layout of child elements (containers or controls) through the use of absolute or relative positioning. Absolute positioning requires definition of X and Y coordinates and permits overlap of elements. Relative positioning lays child elements next to each other either horizontally or vertically. Layout containers include:

- Application: default container provided at the root of your Flex application. There is no need to explicitly define the Application container as it comes part of any Flex application courtesy of the <mx:Application> tag. Organizes child containers vertically, horizontally or absolutely depending on the value of the layout attribute (horizontal, vertical or absolute)

- HBox: organizes child containers or controls horizontally

- VBox: organizes child containers or controls vertically

- HDividedBox: similar to an HBox with the distinction of a draggable divider in between each child container

- VDividedBox: similar to an VBox with the distinction of a draggable divider in between each child container

- Canvas: lays out child containers or controls based on absolute positioning (X and Y coordinates)

- Tile: lays out child containers or controls in columns or rows depending on the value of the direction attribute (horizontal or vertical)

- Panel: Similar to an HBox, VBox or Canvas container depending on the value of the layout attribute (horizontal, vertical or absolute) with the added benefit of a title bar

- Grid: similar to an HTML table it allows organization of child containers as rows and columns of cells

Control Containers

Control containers are used to manage the layout of controls (buttons, combo boxes, etc) only. Control containers include:

- ControlBar: only for use within a Panel or TitleWindow container, the ControlBar manages the layout of controls only (not child containers)

- ApplicationControlBar: one or more ApplicationControlBars may exist in a Flex application, however each must be a direct child of the Application container. Child components are limited to controls.

Navigation Containers

Navigation containers manage the navigation between containers by controlling the visibility of child containers. This visibility control can either be implemented by a nav bar (LinkBar, TabBar, ToggleButtonBar, etc) or by custom event handlers. Navigation containers include:

- Accordion: contains a collection of child containers and manages the visibility of each through the use of accordion headers (similar to nav buttons)

- View Stack: contains a collection of child containers stacked on top of each other. A View Stack is not tied to a particular component responsible for managing visibility but many options exist (i.e LinkBar, TabBar, ToggleButtonBar) for the developer's use

- Tab Navigator: identical to a View Stack except for a built-in navigation feature, TabBar

Containers may serve as a parent container, a child container or both a parent and child container in relation to another container.

The following example demonstrates the simultaneous use of a Canvas container as both a a parent container and a child container.

<mx:VBox width="100%" height="54">
   <mx:Image source="assets/logo.png" />
   <mx:Canvas height="30">
      <mx:Label x="9" y="7" text="Manage Athletes" />
      <mx:Label y="6" text="[ Log Out ]" right="5" />
In most cases, a layout container is not limited to a certain context. Exceptions include the Application container, the ApplicationControlBar container and the ControlBar container.

- Application container: as the root of the Flex application, only one instance of the Application container may exist and can ONLY be a parent container.

- ApplicationControlBar container: as the name suggests, the ApplicationControlBar container defines an area intended to house a control bar for your Flex application. As such, this container can only be defined as a direct child to the Application container.

- ControlBar container: intended to dock a toolbar to a Panel or TitleWindow container, a ControlBar container must be defined as a direct child to a Panel or TitleWindow container

All other containers are available for use in any context. For example, a Canvas container may be defined as a child to a parent VBox, HBox, Tile or even another Canvas container.

Given the hierarchical (parent/child) nature of application layout (containers), best practices suggest the use of MXML (an XML derivative) instead of ActionScript.

Toggling between Design mode and Source mode of Flex Builder, the hierarchical nature of your Flex application will be clear. In Design mode, your Flex application is arranged as nested containers and controls. This arrangement represents a hierarchy (or parent / child structure) and can be verified using the Outline View (Window >> Show View >> Outline). In Source mode, your Flex application is represented in MXML which by nature is hierarchical.

When your Flex application is ultimately translated into ActionScript, another type of hierarchy will emerge - an Object hierarchy. Afterall, a Flex application is nothing more than one Application object composed of other objects composed of other objects...and so on...and MXML is a mapping of your Flex application's object hierarchy to XML.

August 11, 2008

Flex UI State Transitions

Posted by Jeremy Mitchell
Software applications contain a large number of unique views. A view is comprised of structural elements and content arranged according to the designer / developer's preference (layout) and rendered on the user's screen.

Traditional web applications encapsulate each view within an HTML page. In a static website, the number of views correlates directly with the number of HTML pages. For example, a static HTML website with five HTML pages contains five views.

However, the number of views increases exponentially when dynamic capabilities are introduced into the mix. Dynamic capabilities are typically implemented through the use of server-side scripts (ColdFusion, PHP, JSP, .NET, etc).

Server-side scripts analyze data against a predefined set of rules (logic) and generate the view elements (HTML) accordingly. Data may include database data, web services data, cookie data, etc. Therefore, web applications dependent on data for presentation as well as content are commonly referred to as "data-driven" web applications. As the data grows and the number of rules increase so does the number of unique views.

Asynchronous technologies (AJAX) and DOM manipulation via JavaScript (DHTML) also contribute to the increasing number of views.

Flex applications are no different.

However, within the Flex framework, the term "View" refers to the User Interface (UI) as a whole and represents an aggregate of all visual permutations of an application. This naming convention mirrors the convention adopted by a popular Flex architecture, MVC (model-view-controller).

The "View" is comprised of view components (containers & controls) and each structural (or layout) variance to a view component is referred to as a View State. View States apply to all components (controls or containers) that extend the UIComponent class and consequently inherit the states property. The states property is an array of View States for that view component. With a default value of NULL, components start out with only one state, the base state. The base state is the root state of the component and consists only of the properties, styles, event handlers and children that you've originally defined for the component.

Adding View States involves adding one or more State objects to the states property of the component. Each State object requires a name and optionally the name of another state in which it is based on. Exclusion of the basedOn property will base your new state on the base state.

The purpose of a state is to alter the appearance of a component in response to a user or system-initiated event (i.e. click of a button). Altering the appearance of a component involves the use of overrides via a State. Valid overrides include:
  • AddChild
  • RemoveChild
  • SetEventHandler
  • SetProperty
  • SetStyle
When using MXML to define states, overrides are implied and the override tag is not required.

The following example demonstrates the use of an event handler to change the View State of the Application container:

<mx:Application xmlns:mx="" layout="absolute">

<!-- Define State -->
    <mx:State name="newButton">
        <mx:AddChild relativeTo="{h1}" position="firstChild">
            <mx:Button id="buttonNew" label="New Button"/>

<!-- Apply State via event handler -->
<mx:Button id="b1" label="Add a Button" click="currentState='newButton'"/>
The transition from one state to another can be visually enhanced by the use of Transitions. Transitions consist of one or more effects grouped together to play when a state change occurs. Like the states property of a component (control or container), the transitions property is also inherited from the UIComponent class and is data-typed as an array of Transition objects.

Each transition is triggered by a change in a component's state as defined in the fromState and toState properties of a Transition object. Valid values include:
  • A state name
  • An empty string representing the base state
  • An asterisk (*) representing a wildcard matching ALL states
As previously mentioned, the purpose of a transition is to map one or more visual effects to one or more state changes.

Effects come in a variety of flavors and as expected extend the Effect class. Effect types include mask effects (MaskEffect class), sound effects (SoundEffect class) and tween effects (TweenEffect class).

Mask effects include:
  • Iris
  • WipeDown
  • WipeLeft
  • WipeRight
  • WipeUp
Tween effects include:
  • Blur
  • Dissolve
  • Fade
  • Glow
  • Move
  • Pause
  • Resize
  • Rotate
  • Zoom
Sound effects allow you to play an MP3 in response to an event.

Effects can be played in isolation, sequentially (one after another) or in parallel (at the same time). Multiple effects require the creation of a composite effect (CompositeEffect class). Variations of a composite effect may include sequential effects, parallel effects or a combination of both. In either scenario, the component to apply the effects must be defined (target component).

Additional control of each effect is provided through the use of the effect properties. Effect properties include duration, alphaFrom, alphaTo, etc. The details of each effect can be found at the Adobe Flex 3 Language Reference.

The following example demonstrates the use of a state transition:

    <mx:Transition id="myTransition" fromState="*" toState="Advanced">
        <mx:Parallel target="{myVBox}">
            <mx:WipeDown duration="2000"/>
            <mx:Dissolve alphaFrom="0.0" alphaTo="1.0" duration="2000"/>
    <mx:Transition id="yourTransition" fromState="Advanced" toState="*">
        <mx:Sequence target="{myButton}">
            <mx:Zoom duration="1000" zoomHeightTo=".9" zoomWidthTo=".9" />
            <mx:Zoom duration="1000" zoomHeightTo="1" zoomWidthTo="1" />
        </mx:Sequence >
Note that the use of an effect is not limited to a state transition. Effects can be applied to components in the following manner to create behaviors:

<!-- Define Effect -->
<mx:Zoom id="shrink" duration="100" zoomHeightTo=".9" zoomWidthTo=".9" />

<!-- Apply Behavior -->
<mx:Button id="myButton" label="Resize" mouseDownEffect="{shrink}" />
In the previous example, an effect was registered with a trigger (mouseDownEffect) creating a behavior. Trigger + effect = behavior.

As always, the implementation of these Flex features can be achieved via MXML or ActionScript. The decision is yours.

July 16, 2008

Flex CSS Explorer

Posted by Jeremy Mitchell
Skinning and styling a Flex application may be necessary for a number of reasons. The most common reason being the need to satisfy branding requirements. In many instances, styling will be sufficient to establish a unique look and feel for your Flex application, however, we will take a look at both techniques.

Visual components that extend the UIComponent class have skins. These visual components include buttons, layout containers, form controls, navigation elements, etc. Refer to the Flex 3 language reference for additional visual components that subclass the UIComponent class.

A skin represents the visual appearance of a component's state. Many components have only one state while others have many states. Each state has a unique skin. For example, a button component has 8 states (up, over, down, disabled, selected up, selected over, selected down, selected disabled). Each button state has a skin referenced by skin name: upSkin, overSkin, downSkin, disabledSkin, selectedUpSkin, selectedOverSkin, selectedDownSkin, selectedDisabledSkin.

Each component's state has a default skin. The look and feel of your Flex application's default skins is dictated by the application theme. The default theme, Halo, is a combination of skins and style properties. Additional themes included in the Flex 3 SDK include Aeon Graphical, HaloClassic, Ice, Institutional, Smoke and Wooden.

More about included application themes can be found at the Adobe Help Resource Center. To modify the theme color of the default theme (Halo) utilize the themeColor attribute of the Application tag. Valid values include haloOrange, haloBlue, haloSilver, haloGreen as well as valid hexadecimal values (i.e. #FF000). The default theme color is haloBlue.

Custom skins can be applied to components in one of 2 ways:

- graphically
- programatically

Graphical skinning is the most common technique and involves associating an image or SWF with a component's skin. This association can be achieved inline via an MXML attribute or through the use of a style declaration (either embedded in an MXML Script tag or referenced externally in a CSS stylesheet).

Programmatic skinning
requires the use of ActionScript and typically requires a developer to create a new class or extend an existing class. If you are comfortable with ActionScript and writing ActionScript classes, you may find programmatic skinning a better approach. The benefits include increased control over component styles and reduced memory usage.

In addition to skins, components have a wide range of style properties that contribute to their look and feel. Unlike a skin, these style properties are not correlated with a component's state but rather persist across all states of a component. Style properties are defined at the component level in one of 4 ways:

1. Inline MXML
2. Embedded Script tag
3. External CSS Stylesheet
4. SetStyle() method

Flex Builder 3's CSS Explorer provides the tools necessary to skin and style components. With both a Design mode and a Source mode, the CSS Explorer facilitates rapid skinning and styling.

As implied by the name, the CSS Explorer allows a developer to create or modify CSS files. Those familiar with the Flex Style Explorer have experience with CSS editing for Flex using a WYSIWYG editor. The CSS Explorer is very similar with the added benefit of the ability to create or edit component skins.

Creating a CSS stylesheet requires nothing more than selecting a component in CSS Explorer, applying the necessary styles, saving the generated CSS and recompiling your Flex application. The process of applying styles is as follows:

1. Create a CSS file
2. Open the CSS file in Flex Builder 3 (this will launch CSS Explorer)
3. Click on the 'New Style' button
4. Select the component type
5. Modify the component style properties in Design mode (Flex Properties view)
6. View the generated CSS in Source mode
7. Save the CSS file

In addition to styles, Flex developers can apply skins to a component. The process of creating a skin is as follows:

1. Create a CSS file
2. Open the CSS file in Flex Builder 3 (this will launch CSS Explorer)
3. Click on the 'New Style' button
4. Select the component type
5. Press the 'Skin' button in Design mode (Flex Properties view)
6. Enter the type of skin (image or SWF)
7. Choose the location of the image or SWF for each applicable component state
8. Refresh Flex Builder to display the changes to your skin(s)
9. Edit the scale grid to prevent distortion of you skin, if necessary
10. View the generated CSS in Source mode
11. Save the CSS file

Once your skins and / or styles have been defined in your CSS file, simply add a tag similar to the following into your Flex application.

<mx:Script source="styles.css"/>
Now your new look and feel will be applied to your Flex application at compile time.

To dynamically alter your Flex application's look and feel at runtime, review Ted Patrick's entry on runtime CSS.

June 23, 2008

Flex Application Debugger

Posted by Jeremy Mitchell
A familiar activity to all developers involves the undesirable but necessary task of application debugging. Fortunately, Flex Builder provides the tools necessary to easily inspect your code and pinpoint logical or potentially fatal run-time errors.

Successful debugging hinges on the debugging skills of the developer and the debugging tools available to the developer. The former can be acquired only through experience and education while the latter is both a product of the development platform and the community and / or corporate tooling support.

Common debugging techniques include tracing (or printing), breakpoint debugging, step-through debugging and watch expressions. Each of these debugging techniques is supported by Flex Builder.

The Flex Builder Debugging perspective contains a code editor and a set of views designed to aid Flex developers in the debugging process. Flex Builder debugging views include Debug view, Console view, Variables view, Breakpoints view and Expressions view.

Flex Builder Debug View

Outlines the application call stack. Each function is displayed in order of execution (with the bottom of the list being the first function called). The Debug view serves as the control center of the Flex debugger. It allows a developer to start / stop application execution and step over lines of code and step into and out of functions.

Flex Builder Console View

Outputs the results of any trace statements added to your code. Also known as "poor man debugging", trace statements are synonymous with print statements or alert statements. Most developers are very familiar with this debugging technique.

Flex Builder Variables View

Displays variables (simple and complex), their value and data type. By selecting a function in the Debug view, you can inspect the current value of the function's local variables (variables limited in scope to the selected function). Variables outside of the function's scope are also available in the Variables view and are labeled as 'This'. Variable values are also configurable allowing developers to test alternate scenarios in hope of obtaining the desired outcome.

Flex Builder Breakpoints View

Displays a list of application breakpoints. Breakpoints allow developers to inspect the state of an application during execution. Breakpoints can be enabled, disabled or removed in the Breakpoints view.

Flex Builder Expressions View

Allows developers to "watch" specific variables through the life cycle of an application. Variables can be added to the Expressions view by selecting 'Create Watch Expression' in the Variables view for a specific variable.

A Debug session is initiated by clicking the Debug icon found on the Flex Builder toolbar and (by default) runs against the HTML wrapper of a Flex application. Therefore, a debug session requires the use of a web browser. (Change the default web browser by selecting Window > Preferences, then General > Web Browser.) Once a breakpoint is encountered, execution is halted and focus is returned to Flex Builder. At this point a developer can analyze the state of the application and make any necessary changes. Changes may include code changes in the code editor, variable changes in the Variables view, adding new breakpoints, etc. Execution is resumed by clicking 'Continue' in the Debug view. When another breakpoint is encountered, execution is halted once again. In the interim, developers may choose to step over each line of code, step into or out of a function. As this is done, variable values change accordingly. This process continues until the application has run its course or the developer terminates the Debug session.

The Flex debugger is not intended to highlight syntax or data type errors. ActionScript is a compiled language (versus interpreted) and those errors are caught by the compiler at compile time. Rather, the Flex debugger provides valuable insight into a Flex application. Debugging is part of the development process and application transparency is necessary to attain project success. The Flex Builder Application Debugger is a vital part of a successful development life cycle.

June 14, 2008

Flex Builder Basics

Posted by Jeremy Mitchell
A Flex application is the result of one or more MXML and / or ActionScript files compiled into a SWF and delivered via HTTP to the client's browser. The Flex SDK provides everything you need to create Flex applications and is available at no cost to you. Armed with a text editor and the Flex SDK, developers can create simple to complex Flex applications.

The process includes the following steps:
  1. Download the Flex SDK
  2. Create a text file with a .MXML extension to serve as your application root file
  3. Create one or more files with a .MXML extension to dictate your application structure and layout
  4. Create one or more files with a .AS extension to encompass your application functionality
  5. From a command line, launch the Flex compiler to convert your MXML and ActionScript files into a published SWF file
More detailed instructions on command line Flex development can be found at Adobe - Flex Developer Center.

Another more practical option available to Flex developers includes the use of Adobe's Flex Builder. Flex Builder is a fully-functional IDE (Integrated Development Environment) available as a plugin for the Eclipse open-source platform. A stand-alone version of Flex Builder is also available and includes a customized distribution of Eclipse coupled with the Flex Builder plugin.

Priced from $250, Flex Builder 3 provides a host of features designed to improve developer productivity and application quality. Features include:
  1. Coding tools (syntax coloring, code completion, code collapse, code refactoring)
  2. Debugging tools (step-through debugger)
  3. WYSIWYG design tools (prebuilt UI components, drag-and-drop layout manager, application transitions (view states), component property inspector)
  4. Styling / skinning tools (CSS design manager, skin manipulation)
  5. Charting tools
  6. Testing tools
  7. Performance monitoring (profiling) tools
The Flex Builder IDE is organized into three perspectives:
  1. Flex Development perspective
  2. Flex Debugging perspective
  3. Flex Profiling perspective
A Flex Builder perspective is a collection of views and editors utilized to perform a group of related tasks (i.e. development tasks, debugging tasks & performance monitoring (profiling) tasks).

Editors are provided for MXML, ActionScript & CSS code authoring and editing. The MXML & CSS editors operate in two modes - source mode & design mode. The ActionScript editor operates in source mode only. Most developers feel comfortable working with the source code of an application, and therefore, spend a lot of time in source mode. Certain tasks (i.e. web service consumption) require the use of Flex Builder's source mode while other tasks encourage the use of Flex Builder's design mode (i.e. UI layout). However, in many cases the choice is a matter of preference as many tasks can be accomplished in either mode (i.e. UI controls instantiation).

Views encapsulate related functionality required of productive developers. Examples include the ability to visually navigate your application hierarchy (Outline View), display properties for a selected element (Flex Properties View), instantiate containers and controls on-the-fly (Components View), or define application states (States View). Views are also used to organize attributes of a Flex application (i.e. problems, breakpoints, variables, expressions, etc.)

As an Eclipse plugin, Flex Builder integrates seamlessly with other complimentary development tools including Subversion and CVS (source control), ANT (automated build tool), FTP (file transfer), unit testing and more.

With Eclipse and Flex Builder 3, developers have the tools necessary to build high quality, robust business applications.

June 7, 2008

ActionScript Basics

Posted by Jeremy Mitchell
The backbone of the Flex Framework is ActionScript 3.0. An object-oriented scripting language based on the ECMAScript standard, ActionScript defines all of the structure / layout and most of the behavior of your Flex application. (CSS is responsible for the formatting / style and a host of server-side scripting languages (ColdFusion, PHP, JSP, .NET, etc) may contribute to your application's behavior.)

The Flex Framework (or SDK) ships with a library of prebuilt ActionScript classes. These prebuilt classes are organized into packages. A package is a mechanism for organizing ActionScript classes. Each package provides two important benefits:

1. A logical grouping of related functionality. For example, the package labeled mx.controls.listClasses contains the classes responsible for providing list-based control functionality.

2. A namespace for an ActionScript class. Without packages, every class name would have to be unique to avoid ambiguity. If every class name must be unique, a developer must know the name of every prebuilt class to avoid naming conflicts when creating custom classes. With packages, a developer is free to name custom classes as he / she likes as long as the name is unique to the package (namespace).

In most cases your use of prebuilt ActionScript classes will be limited to those found in the mx top level package (i.e. mx.charts.effects or mx.controls.menuClasses). These classes (mx) are specific to Flex applications. However, you'll find that since Flex is a subset of Flash, the ActionScript classes found in the 'flash' top level package can also be leveraged in your Flex application (i.e.

If you have any experience with JavaScript, you'll find ActionScript to be pleasantly familiar. After all, JavaScript and ActionScript are based on the same standard, ECMAScript. Outside of using MXML tags (an abstraction layer for ActionScript), the following techniques are used to include ActionScript into a Flex application:

1. Inline ActionScript – typically limited to property assignment or method calls triggered by an event rather than complex business logic, ActionScript can live within an MXML attribute.

<mx:Button id="myButton" click="eventHandler()" />
2. Nested ActionScript – The text node of an MXML element may contain ActionScript. To avoid the parsing of ActionScript in the text node as XML, place the ActionScript within a CDATA block.

<mx:Button label="click me">
myFunction('hi there')
3. MXML Script Tags – As your ActionScript becomes more complex and verbose, an MXML Script tag may be warranted. Again, a CDATA block must be used to prevent parsing of ActionScript as XML.

import mx.controls.Alert;

public function myFunction(message:String):void {;
4. Adhering to object-oriented principles and guidelines often involves the creation of custom ActionScript classes for use in your Flex application. Custom classes are typically an extension of a prebuilt class and occupy their own file with an .AS extension. Like prebuilt classes, custom classes reside in a package. For custom classes, packages are synonymous with directories. Therefore, a custom class file (i.e. found in wwwroot/com/flexdevelopers/view could be referenced from your Flex application as:
The property / methods of a prebuilt or custom class can be utilized by simply importing the class into your application for use:

import com.flexdeveloper.view.MyClass

var myObject:MyClass = new MyClass();
var myVariable:String = myObject.myMethod();
or, by providing a fully-qualified class path in an ActionScript expression / statement:

if (1==1) { com.flexdeveloper.view.MyClass.myStaticMethod(); }

May 31, 2008

MXML Basics

Posted by Jeremy Mitchell
Arguably, one of the most important parts of the Flex SDK is the Flex Class Library (ActionScript classes categorized and organized into packages). Consisting of numerous ActionScript classes, the Flex Class Library provides a foundation for rapidly building Flex applications.

Dubbed a convenience language, MXML provides developers access to the Flex Class Library through an easy-to-use, easy-to-learn, clean and concise syntax. MXML is simply converted to ActionScript at compile time.

As you may have guessed, MXML follows the convention of XML and, as such, follows the basic syntactical rules of XML.

In many scenarios, using MXML in lieu of ActionScript is considered a best practice. The most popular scenario involves the authoring of application / component layout and structure.

As mentioned earlier, the Flex Class Library is an extensive collection of prebuilt ActionScript classes available for use by your Flex applications. At a very high level, these ActionScript classes provide developers with the ability to accomplish the following:

- Dictate application / component layout and structure
- Style the application / component
- Provide functionality
- Access / parse data

MXML provides an alternate method for Flex development which may be suitable for many scenarios (i.e. application / component layout and structure)

Keep in mind that everything in Flex is derived from an ActionScript class. In other words, every aspect of your Flex application is defined by an instance of an ActionScript class (an object) or by the class itself (static methods, constants, etc). ActionScript is a human-readable, Object-Oriented Programming (OOP) language that when compiled by the Flex compiler is converted into native Flash bytecode and wrapped in a SWF file. This SWF file is ultimately loaded and played by Flash Player 9 embedded in most browsers. Therefore, to build Flex applications, the developer is responsible for the creation and delivery of a collection of ActionScript classes (either prebuilt or custom) to the Flex compiler.

MXML IS ActionScript. MXML is nothing more than an alternate approach to instantiating (creating an object / creating an instance of) a prebuilt or custom ActionScript class for use in a Flex application.

Here is a line of MXML and its ActionScript equivalent.

Creating an instance of the Button class using MXML:

<mx:Button id="myButton" label="Hello" />
Creating an instance of the Button class using ActionScript:

var myButton:Button = new Button();
myButton.label = "Hello";
The MXML is more concise and cleaner in my opinion. In this example, the XML element name (Button) creates a reference variable (named myButton) with reference to a Button object. In MXML, XML attributes typically define the state of the object by setting properties (or instance variables) of the object. Not bad for one short line of code.

Also, as MXML is XML, it makes sense for use in scenarios where parent / child relationships are commonly defined. Application / component layout and structure commonly defines parent / child relationships through use of nested containers and controls, and therefore, makes a great candidate for the use of the XML-based MXML.

May 26, 2008

Flex Overview

Posted by Jeremy Mitchell
Flex is a collection of resources packaged into an SDK (software development kit consisting of the Flex class library (ActionScript classes), the Flex compilers, the debugger, the MXML and ActionScript programming languages, and other utilities) provided by Adobe for use in building expressive and interactive rich internet applications (RIA). By leveraging the Flex SDK and Flex Builder (an Eclipse plugin), developers can create feature-rich, web-based and cross-browser compatible (thanks to Flash Player) applications.

Most applications of any merit consist of client-side functionality and server-side functionality. Traditional web applications utilize Javascript on the client side and a host of scripting languages (ColdFusion, PHP, JSP, .NET, etc) on the server side. Flex applications follow the same model. In fact, the Flex portion of an application (delivered as a SWF file) closely resembles the HTML / Javascript portion of a traditional web application. Flex takes care of the user interface (UI) or the client-side functionality of a web application. Server-side functionality (database interaction, for example) is still dependent on server-side components written in a traditional scripting language (ColdFusion, PHP, JSP, .NET, etc). However, you'll notice that many functions typically handled on the server (i.e. web service consumption) are now handled in the client thanks to Flex.

Web applications that depend too heavily on the server have a negative impact on user experience - specifically applications that require a full-page refresh to interact with the server. As the technology has become available, web applications are shifting a significant amount of work from the server to the client. The result is a highly responsive application providing instant user feedback which results in happier users. Flex-based applications and AJAX-based applications are leading the way.

As developers, one of our goals is to create the files that compose an application. As a whole, these files dictate the layout, structure, style and business logic of an application. In Flex, these files consist primarily of MXML files and ActionScript files (although CSS files play their typical role as stylesheets and Javascript is also available to your Flex app for additional client-side functionality, if necessary).

Best practices suggest the seperation of layout (or structure), style and business logic when developing web-based applications. The same holds true for Flex apps.

A properly-defined Flex app might look like the following*:

- Layout / structure: MXML files and/or ActionScript files
- Style: CSS files
- Client-side business logic: ActionScript files

However, there are exceptions to every rule, and many scenarios justify the use of inline ActionScript inside MXML (layout/structure) files. Similar to the use of inline Javascript inside HTML files, inline ActionScript can be used to provide client-side functionality such as event handling (event handlers) and data binding. However, it is probably best to limit your use of inline ActionScript to simple statements such as method calls or property assignment rather than complex logic. For example:

<mx:Button id="myButton" click="myObject.myFunction()" />
<mx:Button id="myButton" click="currentState='myState'" />
In the first example, a click event dispatched by the myButton instance of the Button class triggers a call to the myFunction method of the myObject instance. In other words, when you click myButton, myFunction is called. The MXML only maps the event to the method. The body of the method may be stored in a separate AS file and, therefore, business logic is successfully separated from layout / structure.

In the second example, a click event dispatched from myButton triggers a simple property assignment (currentState) required to alter the layout / structure using application states. Since this ActionScript statement impacts the layout / structure of the application, one could argue that it's place belongs in the MXML file used to define layout / structure.

When our development is complete, the Flex compiler that ships with Flex Builder generates one or more SWF files based on our MXML files and Actionscript files.


Deploying a Flex application involves the delivery of the SWF file(s) plus an HTML wrapper, the CSS file(s) and any server-side script files (i.e. .CFM, .PHP, etc) to the server. Like traditional web applications, these resources are delivered from the server to the client browser using the customary HTTP request / response fashion.

Check out the animated overview of the Flex development life cycle for a nifty visual of the process.

*Don't forget a complete application usually requires server-side functionality (i.e. database interaction) implemented in the form of server-side scripts (ColdFusion, PHP, JSP, .NET, etc.).