Goal
Add an item to an ArrayCollection when changing states.
Challenge
The AddChild override only works to add visual children to other DisplayObjects, which leaves you with the option to use a SetProperty override to completely replace the source of the ArrayCollection — or you could listen for the enter event on the state and write some ActionScript to manipulate the ArrayCollection.
I’d like something a little more expressive; Something like this:
<mx:state name="moreData"> <AddItem target="{myData}" relativeTo="{myData.getItemAt(2)}" position="after" > <local:Item label="groovy thing" /> </AddItem> </mx:state>
Why?
Consider an application with a MenuBar at the top that lists certain options based on the user’s role/permissions. Since the menu is data-driven, you could create a “manager” state and insert addition options into the menu. And, since states can extend other states, you could base a “regional-manager” state on the “manager” state and add even more options. A RemoveItem override would allow you to base a “assistant-to-the-regional-manager” state on “regional manager” and remove a few things.
Also, once you understand how to create custom overrides, you can do all sorts of things with states that you couldn’t do out of the box. In my case, I wanted the ability to add layer to a data-driven graphic component, so I wrote an AddLayer override.
The Solution
Create an ActionScript class that implements the mx.states.IOverride interface which enforces that you specify how to initialize, apply and remove the override. For adding an item to an ArrayCollection, it’s pretty simple. In apply(), you determine which index the item should be placed at and use ArrayCollection’s addItemAt(item:Object, index:int). Then, in the remove() method you use removeItemAt(item:Object, index:int).

One Comment
Very useful information you got here, thank you for sharing.