enterState

The State class is a small class that is really only used to define the states of a component. It inherits only from EventDispatcher. State has a three public properties: overrides:Array, basedOn:String, and name:String. overrides holds the operations that the State will perform when it is applied to a component. name sets the name of the state and basedOn established a hierarchy between states.

The enterState event is dispatched from the State class when a new state has been entered. The class that actually dispatches this event is UIComponent. State is actually a very small class that exposes an mx_internal method dispatchEnterState() which UIComponent hijacks since it is in charge of applying states to itself:

  1.     private function applyState(stateName:String, lastState:String):void
  2.     {
  3.         var state:State = getState(stateName);
  4.  
  5.         if (stateName == lastState)
  6.             return;
  7.            
  8.         if (state)
  9.         {
  10.             // Apply "basedOn" overrides first
  11.             if (state.basedOn != lastState)
  12.                 applyState(state.basedOn, lastState);
  13.  
  14.             // Apply new state overrides
  15.             var overrides:Array = state.overrides;
  16.  
  17.             for (var i:int = 0; i < overrides.length; i++)
  18.                 overrides[i].apply(this);
  19.  
  20.             // Dispatch the "enterState" event
  21.             state.dispatchEnterState();
  22.         }
  23.     }

This code is called from commitCurrentState() which is also a private method in UIComponent.

Problem:

You have some custom initialization that you need to perform every time a component is added using a State, such as setting focus in a particular field. You need a reliable method of determining that the component has been added.

Solution:

There are two solutions that I've found to work in this case. This first is to add a new public method to the component called activate() and then call it from a handler on the enterState Event. The second is to listen to the addedToStage and updateComplete events, set a flag in addedToStage that you check in updateComplete to run your initialization.

Here is the code, example app, and more detailed explanation.

Search Great Flex/Flash Sites