Archive for 'Flex'

Linked Containers in Flex 4 using Text Layout Framework

Using the latest capabilities of Flash Player 10 in terms of text engine, Text Layout Framework offers much more extensible and feature-rich text layouts. Here is a list of capabilities for the new text framework:

- Bidirectional text, vertical text and over 30 writing scripts including Arabic, Hebrew, Chinese, Japanese, Korean, Thai, Lao, Vietnamese, and others.
- Selection, editing and flowing text across multiple columns and linked containers.
- Vertical text, Tate-Chu-Yoko (horizontal within vertical text) and justifier for East Asian typography.
- Rich typographical controls, including kerning, ligatures, typographic case, digit case, digit width and discretionary hyphens.
- Cut, copy, paste, undo and standard keyboard and mouse gestures for editing
- Rich developer APIs to manipulate text content, layout, markup and create custom text components.
- ActionScript-based object-oriented model for rich text layout enabling live updates.

What we’ll touch in this post is linked containers. What is this all about is that you can have a flow of text (TextFlow) displayed on two or more separate containers and manage them using controllers and composers. From the last sentence we can clearly distinct the three main part of the framework, following MVC approach:

- Model would be the TextFlow along with all it’s elements.
- View would be the container.
- Controller would be the controllers and everything that relates to user interaction on the text.

Starting our demo we want to have 2 containers displayed that will share the same text flow. Sizes for containers will be changed when resizing the application to force the text to span across one or both of them, depending on the size. For the sake of simplicity we will build up a SparkSkin and have everything declared in it.
First we need the TextFlow, an xml file actually that declares the TextFlow. This will be converted into actual text layout format.

1
2
3
4
5
6
7
8
9
10
11
12
13
<fx:Declarations>
    <fx:XML id="xml">
        <TextFlow xmlns="http://ns.adobe.com/textLayout/2008" fontSize="14" fontFamily="Verdana">
            <p>The Text Layout Framework is an extensible ActionScript library, built on the new
               text engine in Adobe® Flash® Player 10 and Adobe AIR 1.5, which delivers advanced,
               easy-to-integrate typographic and text layout features for rich, sophisticated and
               innovative typography on the web. The framework is designed to be used with Adobe
               Flex® or Adobe Flash Professional and is included in Flex 4, code named "Gumbo".
               Developers can use or extend existing components, or use the framework to create
               their own text components.</p>
        </TextFlow>
    </fx:XML>
</fx:Declarations>

Second, we need the containers where the text will be displayed:

1
2
3
4
5
6
<s:Group id="contentGroup" horizontalCenter="0">
   
    <mx:UIComponent id="container1"/>
    <mx:UIComponent id="container2" x="250"/>
   
</s:Group>

As declarations, we have the text flow which will result from converting the xml object and two controllers for the containers we just displayed. These controllers will be used to compute how much text to display in each container, depending on all properties of the text flow.

1
2
3
private var textFlow:TextFlow;
private var controller1:ContainerController;
private var controller2:ContainerController;

At creation complete we just link all components together, converting the text flow, creating controllers for containers and add them to the text flow and update them.

1
2
3
4
5
6
7
8
9
10
11
protected function creationCompleteHandler( event:FlexEvent ):void
{
    textFlow = TextConverter.importToFlow( xml, TextConverter.TEXT_LAYOUT_FORMAT );
    controller1 = new ContainerController( container1 );
    controller2 = new ContainerController( container2 );
   
    textFlow.flowComposer.addController( controller1 );
    textFlow.flowComposer.addController( controller2 );
   
    updateControllers();
}

Updating controllers method is separate because we will also call it when resizing the application:

1
2
3
4
5
6
7
8
9
10
11
12
protected function resizeHandler( event:ResizeEvent ):void
{
    if( initialized )
        updateControllers();
}

private function updateControllers():void
{
    controller1.setCompositionSize( 200, height );
    controller2.setCompositionSize( 200, height );
    textFlow.flowComposer.updateAllControllers();
}

What’s happening is that the controllers will adjust the required sizes depending on the height of the application, and while the containers are linked (with flowCompose.addContainer), text will span across both of them in necessary. You can view the example here http://ayonesoftware.com/blog/examples/tlf with right-click for view source.

Asynchronous Testing using FlexUnit 4

As you might have known there is a new version of FlexUnit in development on the opensource site at Adobe http://opensource.adobe.com/wiki/display/flexunit/FlexUnit for a few months now. This is a new breed between FlexUnit 1 and Fluint. Before delving into the asynchronous topic i would like to mention some improvements to the framework:

1. You are not any more required to explicitly extend TestSuite and TestCase classes. For the suite you just mark it as being a suite by placing [Suite] metadata tag. All test case classes that you want the suite to run should then be added as public properties in this class. The TestCase class does not require having methods that begin with “test”. Instead you mark the test methods by [Test] metadata.

2. The runner is externalized, requiring FlexUnit4UIRunner.swc for default runner. You specify the runner which a suite used by placing [RunWith] metadata tag, default runner looking like [RunWith("org.flexunit.runners.Suite")]. This being the case you can always create a custom runner and add new capabilities/functionalities in test runs.

3. Flash Builder 4 has a built in mechanism for testing, allowing one to choose what suites or test cases to run and display results in FlexUnit Results view. I wouldn’t recommend this approach right now as it has some huge memory issues which eventually will get the builder to a halt.

For a big picture about new capabilities of FlexUnit 4 go to http://opensource.adobe.com/wiki/display/flexunit/FlexUnit+4+feature+overview

Now on the asynchronous area, which has been a lot improved since the addition of Fluint. To mark a method as being part of an async process, you just add “async” under [Test] metadata [Test(async)]. This will let you access the asynchronous capabilities of the framework. The one that we’ll exemplify is usage of a RemoteObject call.

First we build the basic test class:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
package
{
   
import mx.rpc.remoting.RemoteObject;

public class TestRemoteObject
{
    //------------------------------------------------------------
    //
    // Properties
    //
    //------------------------------------------------------------
   
    /**
     * Service to be used in testing async calls.
     * @private
     */

    private static var service:RemoteObject;
   
    //------------------------------------------------------------
    //
    // Methods
    //
    //------------------------------------------------------------
   
    [BeforeClass]
    public static function setUp():void
    {
        service = new RemoteObject();
        service.endpoint = "yourEndpointHere";
    }
}

}

A simple declaration of the RemoteObject and a [BeforeClass] marked method. What [BeforeClass] states is that the method is called only once before the whole class is executed in the test queue. We just setup the RemoteObject with any valid endpoint. The next and final step of the test case is actually testing a method of the service:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
[Test(async)]
public function testMyMethod():void
{
    var token:AsyncToken = service.myMethod();
        token.addResponder( Async.asyncResponder( this,
                                new TestResponder( verifyResult, verifyFault ), 2000 );
}
   
protected function verifyResult( e:ResultEvent, token:AsyncToken ):void
{
    Assert.assertTrue( "Result is what i want it to be", e.result is ArrayCollection );
}
   
protected function verifyFault( e:FaultEvent, token:AsyncToken ):void
{
    Assert.fail( "Unintended fault from service" );
}

Taking it from the in out, we define a TestResponder which is nothing else than a simple Responder, only that it adds an extra parameter “passThroughData” (more on this in a later post) to the result and fault methods. This responder is then added into the async capabilities of the framework using Async.asyncResponder, registering the test case (this – first param), responder (which we just built) and the timeout for call failure. On the verifyResult method you can assert everything you want from the result object and under verifyFault, if this fault is not intentional, you can just Assert.fail, telling the framework that the call failed.

Another goodie about the asynchronous testing in FlexUnit 4 is that you’re no longer needed to chain multiple async methods with events and listeners. You can accomplish this by using “order” param under [Test] metadata. So for the first async method tested you would have [Test(async,order=1)], for the second one [Test(async,order=2)] and so on. The framework will route them handy async one after another.

Next step would be to build the suite class, which as described above should look very simple:

1
2
3
4
5
6
7
8
9
10
11
package
{

[Suite]
[RunWith("org.flexunit.runners.Suite")]
public class TestSuite
{
    public var testRO:TestRemoteObject;
}

}

And the final step is getting everything to work under an Application. The one that does that is FlexUnitCore, which as the name states is the core component coupling the suite and test cases with the runner:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
    xmlns:s="library://ns.adobe.com/flex/spark"
    xmlns:flexUnitUIRunner="http://www.adobe.com/2009/flexUnitUIRunner"
    creationComplete="creationCompleteHandler( event )">
   
        <fx:Script>
        <![CDATA[
   
    import mx.events.FlexEvent;
   
    import org.flexunit.runner.FlexUnitCore;

    protected function creationCompleteHandler( event:FlexEvent ):void
    {
        var core:FlexUnitCore = new FlexUnitCore();
        core.addListener( runner );
       
        core.run( TestSuite );
    }
   
    ]]>
    </fx:Script>
   
    <flexUnitUIRunner:TestRunnerBase id="runner" width="100%" height="100%"/>
   
</s:Application>

The runner, being externalized, is added into the works using core.addListener, thus receiving events from core regarding the tests. Simply call core.run() on the suite and hope that green checks are everywhere. To view the detailed code for async capabilities in FlexUnit go to http://opensource.adobe.com/svn/opensource/flexunit/branches/4.x/FlexUnit4/src/org/flexunit/async/.

Download example source code from here

Flex 4 Layout Capabilities

A major headache in Flex 3 was to slightly change the layout of components. Say you would want to change a List display from vertical to horizontal. No chance. You would need to build up another component, HorizontalList, and have all the logic in there. With the Flex 4 approach to layouts, things are much more simple. Having a layout class that takes care of a component’s children offers support for extensibility. This way there is no difference between a normal vertical list and a horizontal list for example, in terms of data processing/children creations. The only difference is that the components have a different layout attached. This is achieved by specifying the layout property on the component.

The two base components that support layout inside the Flex 4 SDK are:

1. GroupBase, a class for displaying visual elements. Visual elements here means both UIComponent and GraphicElement, elements that can be laid out on the stage.

2. SkinnableDataContainer, a class for displaying visual elements based on data content. This is the base class for all list-based classes on Spark. This is where the journey begins for allowing a List component to display it’s children in different ways.

As the first component is plain simple, we’ll do a demo of customizing a DataContainer’s layout. Let’s suppose we need a menu in a circle fashion like in the image below.
Circle Layout
It looks heavy stuff at a first sight, but all we need is a spark List and a CircleLayout class that computes the positions for each element on the list. The layout class takes in functionalities for measurement/sizing/placing elements on the component.

For positioning and sizing the elements on the stage, setLayoutBoundsPosition and setLayoutBoundsSize would be used. In this process, helper methods are called on the elements when needed to get the preferred size/position such as getPreferredBoundsWidth, getPreferredBoundsHeight. All methods are listed in mx.core.ILayoutElement interface.

For the CircleLayout that we want to build, we only need a radius specified that will help to determine the locations of the elements on a circle.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
/**
 * @private
 */

private var _radius:Number;

/**
 * Circle radius at which the elements will be laid out.
 * @return
 */

public function get radius():Number
{
    return _radius;
}

/**
 * @private
 * @param value
 */

public function set radius( value:Number ):void
{
    _radius = value;
   
    target.invalidateSize();
    target.invalidateDisplayList();
}

The target is the actual component to which the layout is attached. Each time a property is updated that affects the size or display of the component after layout processing, invalidateSize and invalidateDisplayList methods should be called. These are familiar from the Flex 3 invalidation model.
These will translate on calling measure and updateDisplayList on the component which for a ILayoutElement will forward the chain to the layout’s measure and updateDisplayList.

For our example, measure will set the measured width and height on the component based on the radius and sizes for each children elements. As we are not changing anything on a children’s size, we let the components size themselves by using getPreferredBoundsWidth and getPreferredBoundsHeight. Here is the measure method in it’s complete form:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
/**
 * @private
 */

override public function measure():void
{
    super.measure();
   
    target.measuredWidth = radius * 2;
    target.measuredHeight = radius * 2;
   
    var numElements:int = target.numElements;
    var element:ILayoutElement;
   
    for( var i:int = 0; i < numElements; i++ )
    {
        element = target.getElementAt( i );
        element.setLayoutBoundsSize( element.getPreferredBoundsWidth(),
                                     element.getPreferredBoundsHeight() );
    }
}

Now we actually need to place the elements at their specific positions inside updateDisplayList method.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
/**
 * @private
 */

override public function updateDisplayList( width:Number, height:Number ):void
{
    super.updateDisplayList( width, height );
   
    var stepAngle:Number = 360 / getNumLayoutElements();
    var angle:Number;
    var numElements:uint = target.numElements;
    var element:ILayoutElement;
    var x:Number;
    var y:Number;
    var boundsWidth:Number;
    var boundsHeight:Number;
   
    for( var i:int = 0; i < numElements; i++ )
    {
        element = target.getElementAt( i );
       
        if( !element.includeInLayout )
            continue;
       
        DisplayObject( element ).rotation = stepAngle * i;
       
        boundsWidth = element.getPreferredBoundsWidth( true );
        boundsHeight = element.getPreferredBoundsHeight( true );
       
        angle = Math.PI - stepAngle * i * Math.PI / 180;
        x = radius + Math.sin( Math.PI - angle ) * radius - boundsWidth / 2;
        y = radius + Math.sin( Math.PI / 2 - angle ) * radius - boundsHeight / 2;
       
        element.setLayoutBoundsPosition( x, y );
    }
}

Basically what it does it calculates the angles, rotations and positions for each element (if included in layout). One goodie to mention here is the getPreferredBoundsWidth and getPreferredBoundsHeight parameter. This being true, the method will return the value post layout transform. In our case, after the element has been rotated. Other than that it’s pure math.

In a previous post i detailed how the states work in a spark component. Using that knowledge we will have two states for our demo application, one normal state and one selected state. For the selected state, the circle radius will be a little bigger and we’ll display something in the middle.

The list component looks like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<s:List id="list" horizontalCenter="0" verticalCenter="0"
    selectionChanging="listSelectionChangingHandler()"
    skinClass="com.ayone.examples.circleMenu.ui.skins.ListSkin"
    clipAndEnableScrolling="false" labelField="name">
   
    <s:layout>
        <layouts:CircleLayout id="circleLayout" radius.normal="57" radius.selected="200"/>
    </s:layout>
   
    <s:ArrayCollection>
        <fx:Object name="Menu1"/>
        <fx:Object name="Menu2"/>
        <fx:Object name="Menu3"/>
        <fx:Object name="Menu4"/>
        <fx:Object name="Menu5"/>
    </s:ArrayCollection>
   
</s:List>

Note the radius property on the layout is set based on the current state, normal or selected. This along with the invalidation mechanism will assure that the component will have its elements updated each time the state is changed. Using a custom skin to display the ellipse on the list and all is ready:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<s:SparkSkin xmlns:fx="http://ns.adobe.com/mxml/2009" xmlns:s="library://ns.adobe.com/flex/spark"
      minWidth="112" minHeight="112"
      alpha.disabled="0.5">
   
    <s:states>
        <s:State name="normal" />
        <s:State name="disabled" />
    </s:states>
   
    <s:Ellipse top="1" bottom="1" left="1" right="1">
        <s:stroke>
            <s:SolidColorStroke color="0x000000"/>
        </s:stroke>
    </s:Ellipse>
   
    <s:Scroller left="1" top="1" right="1" bottom="1" id="scroller" focusEnabled="false">
        <s:DataGroup id="dataGroup" itemRenderer="spark.skins.default.DefaultItemRenderer">
            <s:layout>
                <s:VerticalLayout gap="0" horizontalAlign="contentJustify" />
            </s:layout>
        </s:DataGroup>
    </s:Scroller>
   
</s:SparkSkin>

And to add a little flavor to it, we’ll animate the transition between states with a MotionPath that basically updates the target property over a period of time.

1
2
3
4
5
6
7
<s:transitions>
    <s:Transition>
        <s:Animate target="{ circleLayout }" duration="200" effectEnd="effectEndHandler(event)">
            <s:SimpleMotionPath property="radius"/>
        </s:Animate>
    </s:Transition>
</s:transitions>

You can view the running application here and view the source here

Architecting a Flex 4 component

One of the biggest improvement in the new version of Flex SDK is the methodology by which you design and implement a component. If in Flex 3 you would probably mix skin mxml code with actionscript logic code, a Flex 4 component has 2 main parts: skin and model/controller. Each of these represent a different object managed by the component itself. The skin part contains mostly the mxml pieces defining the visual elements of the component while the model component handles all the logics and controlling. At the core of a component are the states, which were in Flex 3 also but are way better handled and improved in 4. When starting designing a component, it’s states need to be ruled out and logic that handles them. This is achieved on the actionscript side of code, declaring variables by which states are popped into the stage. Lets get this on one example. Suppose we need a contact form for customers to get feedback. Thinking of it’s functionality it’s clearly that it needs 3 states: default state where initial text is displayed, input state where client has controls for inserting code and final state where thank you and such message is displayed.
Let’s call this component ContactForm, the class definition would then look like this:

1
2
3
4
5
[SkinState( "normal" )]
[SkinState( "input" )]
[SkinState( "final" )]

public class ContactForm extends SkinnableComponent

SkinState metadata specifies what states the skinnable component has, linking them with the states declared in the skin class that looks like this:

1
2
3
4
5
<s:states>
    <mx:State name="normal"/>
    <mx:State name="input"/>
    <mx:State name="final"/>
</s:states>

The next thing would be to declare in the model class all the logic-enabled controls. Logic enabled controls refer to controls that play a role in a component’s lifecycle, such as buttons that trigger state change, text control that offer text for submitting and so on. So lets go ahead and add the skin parts to our component:

1
2
3
4
5
6
7
8
[SkinPart( required="true" )]
public var openInputButton:Button;
   
[SkinPart( required="true")]
public var inputTextArea:TextArea;
   
[SkinPart( required="true" )]
public var submitButton:Button;

Ok. Once we have all the visual elements defined it’s time to work on the logic part of it. Adding boolean properties for ruling out in what state the component should be is a good practice. For the contact form demo component we have only 2, isInput which should tell the component that currentSkinState should be input, and isFinal which reflects the final state where thank you message is displayed. So two new lines to the class:

1
2
private var isInput:Boolean;
private var isFinal:Boolean;

The main skinning method that is overridden is “getCurrentSkinState” which gets called when skin state is invalidated thru “invalidateSkinState”. Basically this method returns the current skin based on the logic properties. Pretty straightforward:

1
2
3
4
5
6
7
8
override protected function getCurrentSkinState():String
{
    if( isFinal )
        return "final";
    else if( isInput )
        return "input";
    else return super.getCurrentSkinState();
}

Now skin parts need a little handling in terms of adding/removing event listeners and other data related computations. These are very handy when designing the component for memory optimization as you can remove event listeners and decouple the component from data area of an application (more on this here). Here they are:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
override protected function partAdded( partName:String, instance:Object ):void
{
    super.partAdded( partName, instance );
       
    if( instance == openInputButton )
        openInputButton.addEventListener( MouseEvent.CLICK, openInputButtonClickHandler );
    else if( instance == submitButton )
        submitButton.addEventListener( MouseEvent.CLICK, submitButtonClickHandler );
}
   
override protected function partRemoved( partName:String, instance:Object ):void
{
    super.partRemoved( partName, instance );
       
    if( instance == openInputButton )
        openInputButton.removeEventListener( MouseEvent.CLICK, openInputButtonClickHandler );
}

And here are the event handlers that rule out the transitions between component states:

1
2
3
4
5
6
7
8
9
10
11
12
private function openInputButtonClickHandler( e:MouseEvent ):void
{
    isInput = true;
    invalidateSkinState();
}
   
private function submitButtonClickHandler( e:MouseEvent ):void
{
    isInput = false;
    isFinal = true;
    invalidateSkinState();
}

What happens under the hood is that when “invalidateSkinState()” gets called, framework will eventually call “getCurrentSkinState” and based on the state received it invalidates the skin and update based on that value.
These is pretty much it on the model class. It should look like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
package com.ayone.examples.contactForm.ui
{

import flash.events.MouseEvent;

import spark.components.Button;
import spark.components.TextArea;
import spark.components.supportClasses.SkinnableComponent;

[SkinState( "normal" )]

[SkinState( "input" )]

[SkinState( "final" )]

public class ContactForm extends SkinnableComponent
{
    //------------------------------------------------------------
    //
    // Properties
    //
    //------------------------------------------------------------
   
    //------------------------------
    // Skin Parts
    //------------------------------
   
    [SkinPart( required="true" )]
    public var openInputButton:Button;
   
    [SkinPart( required="true")]
    public var inputTextArea:TextArea;
   
    [SkinPart( required="true" )]
    public var submitButton:Button;
   
    //------------------------------
    // State Related Logic
    //------------------------------
   
    private var isInput:Boolean;
   
    private var isFinal:Boolean;
   
    //------------------------------------------------------------
    //
    // Methods
    //
    //------------------------------------------------------------
   
    //------------------------------------------------------------
    // Skinning
    //------------------------------------------------------------
   
    override protected function getCurrentSkinState():String
    {
        if( isFinal )
            return "final";
        else if( isInput )
            return "input";
        else return super.getCurrentSkinState();
    }
   
    override protected function partAdded( partName:String, instance:Object ):void
    {
        super.partAdded( partName, instance );
       
        if( instance == openInputButton )
            openInputButton.addEventListener( MouseEvent.CLICK, openInputButtonClickHandler );
        else if( instance == submitButton )
            submitButton.addEventListener( MouseEvent.CLICK, submitButtonClickHandler );
    }
   
    override protected function partRemoved( partName:String, instance:Object ):void
    {
        super.partRemoved( partName, instance );
       
        if( instance == openInputButton )
            openInputButton.removeEventListener( MouseEvent.CLICK, openInputButtonClickHandler );
    }
   
    //------------------------------------------------------------
    // Event Handling
    //------------------------------------------------------------
   
    private function openInputButtonClickHandler( e:MouseEvent ):void
    {
        isInput = true;
        invalidateSkinState();
    }
   
    private function submitButtonClickHandler( e:MouseEvent ):void
    {
        isInput = false;
        isFinal = true;
        invalidateSkinState();
    }
}

}

But wait there’s more. We still didn’t rule out the skin class. First thing to be added is the state declaration which links the states from the main class to skin class:

1
2
3
4
5
<s:states>
    <mx:State name="normal"/>
    <mx:State name="input"/>
    <mx:State name="final"/>
</s:states>

Nothing new here. The newly addition to the state management in Flex 4 is the state-related properties that enables one to set let’s say height for a skin depending on what state it is. Something like this:

1
2
3
<s:SparkSkin xmlns:fx="http://ns.adobe.com/mxml/2009" xmlns:s="library://ns.adobe.com/flex/spark"
    xmlns:mx="library://ns.adobe.com/flex/halo"
    width="400" height="30" height.input="200">

Notice the two height declaration that are translated like this: height in “input” state should be 200 and 30 in any other state. All we need to do now is declaring the visual elements that forms the skin:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<s:Group includeIn="normal" width="100%" height="100%">
    <s:layout>
        <s:HorizontalLayout verticalAlign="middle"/>
    </s:layout>
    <s:SimpleText text="Click here to get in touch with us"/>
    <s:Button label="Contact" id="openInputButton"/>   
</s:Group>

<s:Group includeIn="input" width="100%" height="100%">
    <s:layout>
        <s:VerticalLayout horizontalAlign="right"/>
    </s:layout>
    <s:TextArea id="inputTextArea" width="100%"/>
    <s:Button id="submitButton" label="Send"/>
</s:Group>

<s:SimpleText includeIn="final" text="Thank you for contacting us"/>

Note that actual skin parts declared in main class don’t have any property related to state management. Instead those are wrapped in Group components and those are state-enabled thru “includeIn” property. “includeIn” basically states that a visual element should be present only in that specific state (or state group, more on that in a future post). And this is the beauty of it, once the main class has defined the skin parts that it requires for a functional component, you can mix and play with the skin as much as you want.

That would be pretty much it. You can download the source code from here.

Flex 4 Memory Optimizations

One of the most problematic and discussed area in Flex development is garbage collection and memory optimization. Even with new tools added to Flex Builder (now Flash Builder) like Profiling, struggling to obtain a memory clear application is not easy. One of the methods is the undocumented hack with LocalConnection
where you connect two of them and do nothing at all after.

1
2
3
4
5
6
7
8
9
try
{
    var lc1:LocalConnection = new LocalConnection();
    var lc2:LocalConnection = new LocalConnection();

    lc1.connect( "gcConnection" );
    lc2.connect( "gcConnection" );
}
catch (e:Error) {}

This will trigger the internal garbage collection and clear everything that is decoupled from application.
But doing just this doesn’t mean your code will work as expected. The whole architecture needs to be ruled out with GC in mind and here is where the Flex 4 framework came in big help. Offering methods like partAdded() and partRemoved() to skinnable components is a path that assures every listener added to skin parts is removed in partRemoved(). This means if you show/hide some parts without removing the whole component from stage, all you need to do is call partRemoved() and partAdded() on the part you need to garbage collect. Make sure you call theese methods only if the part exists first as the first partAdded() is called from withing the component. This technique applies mostly to DataGroup where itemRenderers are used and bound with data that might have a longer lifespan than the renderer itself. Another critical time where some extra logic for memory should be added is when renderer is removed from stage, aka when “data” property is set to null. Here is where you might want to call detachSkin() to make sure all parts are decouples from the external resources and available for garbage collection.

Another handy method relates to images, components that are very problematic when comes to garbage collecting, where there is a new functionality inserted in Flash Player 10. SWFLoader has an unloadAndStop method that takes “invokeGarbageCollector” as a param which eventually result in calling “unloadAndStop” method available in Flash Player 10.

Working on a data intensive project in Flex 4 i’ve noticed that the framework better supports memory optimization that it did before so kudos for SDK guys. Will get back here with any interesting idea related to garbage collector in Flex 4 and where is the next critical place where you need to do extra work for it.