By default, all states are based on the base state. For example, the new
checkbox in Example 12-1 and Example 12-2 from the preceding section is
added to the VBox
. When the new state
is applied, the VBox
and nested button
from the base state continue to exist. However, note that states are not
applied cumulatively. For instance, Example 12-3 defines two states in
addition to the base state. The base state has two buttons. Each button
applies one of the states. When applying the newCheckbox
state, a new checkbox is added. When applying the newTextArea
state, a new text area is added, but if the checkbox had been
previously added, it is removed.
Example 12-3. Defining a state that is not based on an existing state
<?xml version="1.0" encoding="utf-8"?> <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute"> <mx:VBox id="vbox"> <mx:Button label="Add Checkbox" click="currentState='newCheckbox';" /> <mx:Button label="Add Text Area" click="currentState='newTextArea';" /> </mx:VBox> <mx:states> <mx:State name="newCheckbox"> <mx:AddChild relativeTo="{vbox}"> <mx:CheckBox id="checkbox" label="New Checkbox" /> </mx:AddChild> </mx:State> <mx:State name="newTextArea"> <mx:AddChild relativeTo="{vbox}"> <mx:TextArea id="textarea" /> </mx:AddChild> </mx:State> </mx:states> </mx:Application>
When components are removed by changing states, the components are still stored in memory. Once a
component has been created, moving away from the state in which it is
created is the equivalent of calling the removeChild()
method in ActionScript: the
component is removed from the display list, but it still exists in
memory.
Figure 12-3 and Figure 12-4 show what these two states look like. You’ll notice that only one of the components (checkbox or text area) gets added at a time.
If you want to define a state so that it’s based on a state other
than the base state, use the basedOn
attribute
of the <mx:State>
tag. You can assign the name of a state to the basedOn
attribute of a different state, and the
state with the basedOn
value
automatically inherits the state’s overrides, specified in the basedOn
attribute. For example, rewrite the
newTextArea
state definition so that
the <mx:State>
tag appears as
follows:
<mx:State name="newTextArea" basedOn="newCheckbox">
When the newTextArea
state is
rewritten with the basedOn
attribute
(as in the preceding line of code), the newTextArea
state adds both a checkbox and a
text area. Figure 12-5
shows the newTextArea
state now that
it’s based on newCheckbox
.