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: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 name="clearState" basedOn="">
        <mx:SetProperty target="{submitButton}" name="label" value="clear" />
        <mx:SetEventHandler target="{submitButton}" name="click" handler="emptyDocument()" />
        <mx:RemoveChild target="{submitButton}"/>

<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:State name="submitState" />
     <s:State name="clearState" />

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"/>

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 Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: