Вы находитесь на странице: 1из 12

Web 2.

0 & Rich Internet Applications


Framework Fundamentals

Understanding the Flex Application Life Cycle


Although its possible to build some Flex applications without having an understanding of the
application life cycle, It will help us to know the basic mechanics and the order in which
things occur. This will help us configure features such as customized preloaders, do things
such as load other Flex applications at runtime and manage the process of loading and
unloading class libraries and assets at runtime.
A good understanding of the Flex application life cycle will enable us to build better
applications because we will know where to optimally run code.
The root of a Flex application is typically SystemManager, which is a subclass of
flash.display.MovieClip, a Flash Player display object type.
Basic application startup event flow

Fig: Basic application startup event flow

The .swf format is a progressive download format, which means that Flash Player can
access content on frames as they download without having to wait for the entire file to
download
SystemManager has two frames
The first frame is used to display a progress indicator while the application loads.
This frame is lightweight in terms of file size so that it can download and run almost
immediately, and it does not house much of the Flex framework.
The second frame is the one in which the application itself is actually housed.
It creates an instance of the main application class for the Flex application.
All the application objects internal life cycle events occur.

Page 1

Web 2.0 & Rich Internet Applications


Framework Fundamentals
The internal life cycle events are as follows:
Preinitialize
The application has been instantiated but has not yet created any child components.
Initialize
The application has created child components but has not yet laid out those
components.
CreationComplete
The application has been completely instantiated and has laid out all components.

Once an application has completed its internal startup procedure, it notifies


SystemManager, which dispatches an application Complete event.
From that point forward, the application is ready to run.
SystemManager also manages all things that are displayed in front of the application
content.
This means that all pop ups, cursors, and tool tips are placed within the
SystemManager instance.

Differentiating Between Flash Player and Framework

One of the most important concepts to understand about Flex is the relationship
between the Flex framework and Flash Player.
Distinguishing between these things is not difficult once you have an understanding of
the basic differentiators.
Flash Player is a runtime environment for Flash and Flex applications.
Flash and Flex applications can do only what Flash Player allows them to do.
Flash Player provides an API for all the operations it can perform.
Flex applications run in the same Flash Player as Flash applications.
That means the .swf files for Flex applications cannot contain anything that a standard
Flash application cant contain, and therefore, both applications have the same
behaviors.
Therefore, what differentiates Flash and Flex applications is not the content, but how
you create that content.
We can easily differentiate between Flash Player and Flex framework classes using
these guidelines:
If the class is in a package starting with the word flash (e.g., flash.net.URLLoader), it
is part of Flash Player.
If the class is in a package starting with the letters mx (e.g., mx.controls.Button), it is
part of the Flex framework.

Page 2

Web 2.0 & Rich Internet Applications


Framework Fundamentals

MXML tags almost always (with few exceptions) correspond to flex framework
classes.

Bootstrapping Flex Applications

Although it would be natural enough to assume that the root of a Flex application is
an Application object.
But the default root object is, in fact, of type mx.managers.SystemManager.
In order to understand SystemManager and the bootstrapping process, we have to
understand just a little about a Flash Player class called flash.display.MovieClip.
The MovieClip class is a display object type which allows you to programmatically
work with timelines.
A timeline is composed of frames. A frame represents a point in time during the
playback of a timeline.
Because theres no way to programmatically add frames, almost all display objects in
Flex applications consist of just one frame.
SystemManager is the one exception to this rule.
SystemManager consists of two frames.
This is essential because it enables the Flex application to have a preloader that
indicates download progress to the user.
The preloader must exist on the first frame, and the Flex application (the Application
object) must exist on the second frame.
Flex automatically handles all the bootstrapping and initialization, including creation
of the SystemManager object and the default preloader.

Loading One Flex Application into another Flex Application


Loading one Flex application into another Flex application is actually simple.
<mx:SWFLoader source="application.swf" />
It gets slightly more challenging when you want to interact with the content you are loading.
What is the path to the loaded application relative to the SWFLoader used to load the
application?
When has the loaded application actually initialized?
When an SWFLoader loads a Flex application, the SWFLoader objects content
property provides a reference to the root of the loaded Flex application.
The SystemManager class defines an application property that references the
Application object.
When an SWFLoader loads and initializes the content, it dispatches an init event.
We should first handle the init event. This tells us when we can reference the
SystemManager for the loaded content.
Page 3

Web 2.0 & Rich Internet Applications


Framework Fundamentals
We must then add an event listener for the applicationComplete event for the
SystemManager.
When the applicationComplete event occurs, we can reference the Application object
for the loaded content.
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute">
<mx:Script>
<![CDATA[
public function setBackground(color:Number):void {
canvas.setStyle("backgroundColor", color);
}
]]>
</mx:Script>
<mx:Canvas id="canvas" backgroundColor="#FFFFFF" width="100" height="100"/>
</mx:Application>

<?xml version="1.0" encoding="utf-8"?>


<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute">
<mx:Script>
<![CDATA[
import mx.managers.SystemManager;
import mx.events.FlexEvent;
private function initHandler(event:Event):void {
event.target.content.addEventListener(FlexEvent.APPLICATION_COMPLETE,
applicationCompleteHandler);
}
private function applicationCompleteHandler(event:Event):void {
event.target.application.setBackground(0xFFFF00);
Page 4

Web 2.0 & Rich Internet Applications


Framework Fundamentals
}
]]>
</mx:Script>
<mx:SWFLoader source="B.swf" init="initHandler(event)" />
</mx:Application>

Understanding Application Domains

An application domain is the partition within which an application runs in Flash


Player.
Just one application is running in Flash Player, and in such cases, there is just one
application domain.
When you load additional .swf files into an existing application, you can create
additional application domains for some or all of those additional applications.

When we load a .swf file, three possible things can occur:


The loaded .swf runs in a new application domain that is completely partitioned from
all other application domains.
The loaded .swf runs in a new application domain that is a child of an existing
application domain.
The loaded .swf runs in an existing application domain.
var context:LoaderContext = new LoaderContext( );
context.applicationDomain=new
ApplicationDomain(ApplicationDomain.currentDomain);
var request:URLRequest = new URLRequest("RuntimeLoadingExample.swf");
var loader:Loader = new Loader( );
loader.load(request, context);

var context:LoaderContext = new LoaderContext( );


context.applicationDomain = new ApplicationDomain( );
var request:URLRequest = new URLRequest("RuntimeLoadingExample.swf");
var loader:Loader = new Loader( );
loader.load(request, context);

Page 5

Web 2.0 & Rich Internet Applications


Framework Fundamentals
var context:LoaderContext = new LoaderContext( );
context.applicationDomain = ApplicationDomain.currentDomain;
var request:URLRequest = new URLRequest("RuntimeLoadingExample.swf");
var loader:Loader = new Loader( );
loader.load(request, context);

Understanding the Preloader

All Flex applications have a preloader with a progress bar that indicates progress as
the application loads and initializes.
This preloader is a lightweight class that is created on the first frame of the system
manager.
The preloader dispatches a series of events that the progress bar then handles.

The following are valid events for preloaders:

Progress
Indicates download progress
Complete
Indicates that the download is complete
rslError
Indicates that a runtime shared library could not load
rslProgress
Indicates the download progress for a runtime shared library
rslComplete
Indicates that the download is complete for runtime shared libraries
initProgress
Indicates that the application is initializing
initComplete
Indicates that the application has initialized

Managing Layout
An overview of Flex layout containers and discuss the layout rules used by containers. We
will see how to work with containers and children, nesting containers, and building fluid
interfaces.

Flex Layout Overview


Container components are the basis of how Flex provides layout logic.
Page 6

Web 2.0 & Rich Internet Applications


Framework Fundamentals
At the most basic level, the Application class is a container, and subitems within the
Application class (tag) are called children.
In the following code two children are added to the Application container a TextInput
instance and a Button instance:
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:TextInput/>
<mx:Button label="Submit"/>
</mx:Application>
Adding children to a container using ActionScript
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx=
"http://www.adobe.com/2006/mxml" initialize="addItems( )">
<mx:Script>
<![CDATA[
import mx.controls.Button;
import mx.controls.TextInput;
private function addItems( ):void
{
var ti:TextInput = new TextInput( );
this.addChild(ti);
var btn:Button = new Button( );
btn.label = "Submit";
this.addChild(btn);
}
]]>
</mx:Script>
</mx:Application>
Page 7

Web 2.0 & Rich Internet Applications


Framework Fundamentals

Working with Children

In addition to adding children, we can also remove, reorder, and retrieve the children
of a container.
Setting up the initial state of a container via MXML is simple enough.
But managing change afterward requires a better understanding of the ActionScript
display list API

The methods:

addChild( ),
addChildAt( )
getChildAt( ),
getChildByName( ),
getChildIndex( )
getChildren( ),
removeAllChildren( ),
contains( ),
setChildIndex( )
numChildren
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:Script>
<![CDATA[
private function moveToTheBeginning( ):void
{
// Retrieve the index of the last child, child indices are zero-based
var lastChildIndex:int = tileOfLabels.numChildren - 1;
// Get a reference to the last child
var child:DisplayObject = tileOfLabels.getChildAt(lastChildIndex);
// Change the index of the child
tileOfLabels.setChildIndex(child,0);
}
Page 8

Web 2.0 & Rich Internet Applications


Framework Fundamentals
]]>
</mx:Script>
<mx:Tile id="tileOfLabels">
<mx:Label text="1"/>
<mx:Label text="2"/>
<mx:Label text="3"/>
<mx:Label text="4"/>
<mx:Label text="5"/>
<mx:Label text="6"/>
</mx:Tile>
<mx:Button label="Move to the beginning" click="moveToTheBeginning(
)"/>
</mx:Application>

First, the initial layout contains six buttons within a Tile container, each labeled
according to its order within the Tile.
A button at the bottom is used to call a function to move the last child to the
beginning of the Tile container.
In moveToTheBeginning( ), the index of the last child is retrieved, which is zerobased
Next, a reference to the last child in the display list is obtained using getChildAt( ).
After the last child index is retrieved, setChildIndex( ) is called and passes a reference
to the button instance and a new index.

Container Types

Every container provided by the Flex framework has a set of rules by which it lays out
its children.
Flex uses these rules to measure the available space for children, and to decide where
children are positioned.
A VBox container, for example, arranges its children vertically, placing only one item
per row.
An HBox container arranges its children horizontally.
Knowing when to use a particular container is important as you build your Flex
applications.

Page 9

Web 2.0 & Rich Internet Applications


Framework Fundamentals

Layout Rules

Many containers internally make use of two main layout rules: box and canvas.
These rules define how containers internally implement child positioning and sizing.
Understanding the different layout rules will help us to understand how layout
containers work, and to develop application layouts more effectively.
Layout rules are executed when children containers are initially instantiated, anytime
children are added or removed, and whenever a container is resized.
The only time that is not the case is when the auto Layout property is set to false.
In this case, the layout rules execute only on initialization, and when children are
added or removed.
When layout rules are executing, they go through two steps.
First, the container measures the space needed for each child.
This allows the container to decide how much space it needs in order to best fit all of
its children, and it allows the container to decide where everything should be
positioned if it is responsible for positioning the children.
During this process, if a childs includeInLayout property is set to false, the child will
be ignored and wont be factored into the positioning of children.
In the second step, the container repositions and sizes the children as needed.

Box-based layout

The containers HBox, VBox, HDividedBox, VDividedBox, ApplicationControlBar,


and ControlBar all base their layout rules on those of the Box container.
For this reason, we will often find they are often referred to as box-based layout
containers.
Page 10

Web 2.0 & Rich Internet Applications


Framework Fundamentals

The box layout rule dictates that each child occupies its own row or column,
depending on the direction under which the rule is operating.
The two directions supported are vertical and horizontal. All box-based layout
containers implement the direction property.
The default value of the direction property depends on the container.
We can set the value of the direction property to horizontal or vertical using the
constant values BoxDirection.HORIZONTAL and BoxDirection.VERTICAL

In this layout rule, the size of the container depends on a few factors:
If the container has a target width and height, those values are used to set the size.
If the size that is set is smaller than the area needed for the children to be displayed, a
scrollbar is automatically displayed unless scrollPolicy is set to ScrollPolicy.OFF.
If no size is explicitly set, the container attempts to expand as needed within the
available space. If enough space is not available, a scrollbar is used to allow the user
access to the content.

Canvas-based layout

The Canvas container is the base implementer of the canvas-based layout rule.
Though simple, it is an important layout container to discuss because its rules are used
by other containers.
Canvas-based layout allows us to position children using explicit x and y coordinates.
This allows us to accurately control the position of each child.
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:Canvas>
<mx:Label x="0" y="50" text="Enter your name:"/>
<mx:TextInput x="110" y="50"/>
</mx:Canvas>
</mx:Application>

Constraint-based layout.

Canvas also supports the ability to lay out children using what is called constraintbased layout.
Constraint-based layout lets you lay out children at predefined positions relative to
their parent.
Page 11

Web 2.0 & Rich Internet Applications


Framework Fundamentals

This gives you the flexibility of positioning children in a predefined position while at
the same time repositioning them as needed to satisfy the constraints set.
This tends to be a more practical method of accurately positioning children than
simply supplying a specific location, because it allows the container to resize
according to the maximum available real estate
To position children using the constraint-based layout method, you set one or several
child style properties top, bottom, left, right, horizontalCenter, and verticalCenter
with a value based on the parents position in relation to the child.
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:Canvas width="100%" height="100%">
<mx:Button right="10" label="Right Most Button"/>
<mx:Button right="10" bottom="10" label="Right Bottom Most Button"/>
</mx:Canvas>
</mx:Application>

Here are some additional things to remember concerning constraint-based layouts:


Setting the top style property causes the childs y value to be set to that many pixels
away from the parent containers top edge.
Setting the bottom style property causes the y property of the child to be set to the
height of the container, minus the childs height.
You can set both the bottom and the top values of a child, which automatically resizes
the child height and remains within the top and bottom constraints.
Setting the left style property sets the x value of the child at runtime to that many
pixels away from the parents edge.
Setting the right style property at runtime sets the x value to the total width of the
container minus the right value and the width of the child.

Page 12

Вам также может понравиться