New in Flex 4 – Part 1 – States

Now that Flex 4 beta 2 is stable enough, I decided to start a series of posts describing the changes that were applied to Flex 4.

Today’s topic is – States!

OK, so first let’s review how we used to define states in Flex 3.
Inside the <mx:states> tags, we could define states, and for each state define properties, styles and event listeners and even add or remove childs:

<mx:states>
   <mx:State name="submitState" basedOn="">
        <mx:SetProperty target="{submitButton}" name="label" value="submit" />
        <mx:SetStyle target="{submitButton}" name="textDecoration" value="underline"/>
        <mx:SetEventHandler target="{submitButton}" name="click" handler="trace('done');"/>
    </mx:State>
    <mx:State name="clearState" basedOn="">
        <mx:SetProperty target="{submitButton}" name="label" value="clear" />
        <mx:SetEventHandler target="{submitButton}" name="click" handler="emptyDocument()" />
        <mx:RemoveChild target="{submitButton}"/>
    </mx:State>
</mx:states>

<mx:Button id="submitButton" />

It’s a simple example of a submit button that gets some styling, property and event handler set in submit state, and others before it is removed in clear state.

This is done completely different when writing states in Flex 4.
When using the MXML2009 namespace:

1. Only states are defined within the <s:states> tags.

<s:states>
     <s:State name="submitState" />
     <s:State name="clearState" />
</s:states>

2. You can’t use addChild and removeChild within a state definition. Instead, you use the new attributes includeIn and excludeFrom within the component definition itself to define it’s role in the different states.

<s:Group id="loginForm" >
     <s:Button label="submit" bottom="10" right="10" includeIn="submitState"/>
</s:Group>

3. SetProperty, SetStyle and SetEventHandler were replaced with a “dot” syntax to allow setting attributes to component in the context of a state.

<s:Button label.submitState="submit" label.clearState="clear"
     textDecoration.submitState="underline" textDecoration.clearState="none"
     click.submitState="trace('done')" click.clearState="trace('cleared')"
    />

Note I didn’t specify that the button should be included in the submit state (using includeIn=”submitState” attribute). This is because a component can no longer belong to a null state. By default, the first defined state (submitState in our example) is set to be the initial state of the component.

A good complete code example to see this in action is the spark.skins.spark.ButtonSkin, check it out!

Leave a comment