Flex 4 States: The Default State?

You can call the first state in your list of states the default as Adobe’s Kevin Hoyt does in his article about States, and as Stephen Gilson does in his Flex Doc article, but don’t expect it to always have your back. I found this out the usual way, I assumed and failed.

The Actionscript 3.0 reference docs for mx.states.State don’t clarify this issue, though it does make one reference to a “default view state”.

Let’s say you have a component with 3 states:

  1.  
  2. <s:states>
  3. <s:State name="welcome"/>
  4. <s:State name="top_products"/>
  5. <s:State name="all_products"/>
  6. </s:states>
  7.  


And you have two ArrayCollections of Products, allProducts and topProducts, that will be bound to a DataGroup depending on the currentState of the view.

  1.  
  2. <s:DataGroup id="productsDataGroup"
  3. dataProvider="{allProducts}"
  4. dataProvider.top_products="{topProducts}"
  5. ... />
  6.  


As you can see above I’ve declared the “main” dataProvider and a dataProvider for the state “top_products”. What data do you expect to get bound when I change currentState to “all_products” or even “welcome”? It will go back to allProducts. Great, that’s what I want.

BUT…

If the allProducts ArrayCollection has been changed in the meantime, the DataGroup will not rebind the allProducts collection, so I’ll be looking at old data.

The way to make sure the binding occurs as expected, and updates are reflected, is to get in the habit of being explicit.

  1.  
  2. <s:DataGroup id="productsDataGroup"
  3. dataProvider="{allProducts}"
  4. dataProvider.welcome="{allProducts}"
  5. dataProvider.top_products="{topProducts}"
  6. dataProvider.all_products="{allProducts}"
  7. ... />
  8.  


Setting currentState in the component tag declaration is a good practice to make sure you start off in the right view. The consensus yesterday from conversations on Twitter is that the initial currentState will be the first state listed in the declaration. But this is not a default you can rely on once things start changing.

When it comes to setting data providers, you are best off being explicit if you’re going to assign different sources based on state.

Thanks to @jamespolanco, @pollensoft, @derrickgrigg, @benjamminSTL, and @flexmonkeypatch for your contributions to the discussion.


FlexPermalink

Name:

Email:

Location:

URL:

Smileys

Remember my personal information

Notify me of follow-up comments?