Flex element includein

2019-08-17 20:10发布

问题:

In Flex, we can assign state to an element via this:

<s:Button id="mybtn" includeIn="mystate" label="button label"/>

How can we do the includeIn with ActionScript?

Thank you.

回答1:

States are an MXML concept, not an AS concept. In AS you have to write your own logic in the override function set currentState.

override public function set currentState(value:String):void
{
  super.currentState = value;
  //write your logic for states
}


回答2:

The includeIn pseudo-attribute only exists in the MXML language. I call it a pseudo-attribute because it does not map to a property or a style (of the Button class in your example).

Instead it is a shorthand notation of the old mx AddItems tag. In that syntax your example would look something like this:

<mx:states>
    <mx:State name="normal"/>
    <mx:State name="mystate">
        <mx:AddItems items="{mybtn}"/>
    </mx:State>
</mx:states>

<mx:Button id="mybtn"/>

I mention this, because the ActionScript code that is generated for includeIn is very similar. This is what it looks like:

states = [
    new State ({
        name: "normal",
        overrides: []
    }),
    new State ({
        name: "mystate",
        overrides: [
          new AddItems().initializeFromObject({
            itemsFactory: _TestFlex_Button1_factory,
            destination: null,
            position: "first"
          })
        ]
    })
];

The difference is that it uses a factory to instantiate the Button.
Note that if you're interested in the ActionScript code that is generated from MXML code, you can have a look at it simply by passing the keep-generated-actionscript flag to the compiler (see mxmlc compiler options).

Of course if you really want to 'manually' write that logic (I wouldn't), it may be easier to override setCurrentState() or listen for the CURRENT_STATE_CHANGE event, and call addElement() or removeElement() depending on the value of currentState.