开发者

What is Flex good practice to change another component's state?

I currently use: Flexglobals.toplevelapplication.component1.compnent2.currentState = 'some开发者_JAVA百科thing';

is there a better way of doing do? Can I bind the state of a components to variable in my model?


Ideally, components should be self contained little pieces of your application. One component shouldn't have any effect (including changing the state) on any component, except possibly it's children.

The "Encapsulation proper" approach to change the state of an unrelated component is to dispatch an event from the component. The component's parent (or some component higher up in the hierarchy chain) is going to execute an event listener and change that state of the appropriate component, by either calling a method on the component that needs a state change or changing a property on the component that needs a state change.

If you have a complicated hierarchy, this approach can lead to a lot of tedium, creating events up the chain, and creating properties / methods down the chain in order to preserve encapsulation. Some frameworks, such as Cairngorm introduce a global singleton to avoid this tedium. In Cairngorm that singleton is the ModelLocator.

The ModeLlocator is, basically, a global dependency in your application. You can give any component access to it, and through the use of binding if a property is changed in one place, it an be automatically updated elsewhere. To change the state using binding, use an approach like this:

In the ModelLocator, create a variable to hold the state for the view in question:

[Bindable]
public var comp1State : String = 'defaultState';

In comp1 do something like this:

<mx:Container currentState="{model.comp1State}" otherComponentProperties>
 <!-- other component code including defining the states -->
</mx:Container>

Then in the component where you want to change the state, do something like this:

model.comp1State = 'nextState'

Binding will take it from here. I wouldn't use his approach lightly though. It depends on the component you're trying to create and how much you car about reuse. The most common way I've seen this implemented is not with states, but with the selectedIndex in a ViewStack. But, the approach would be the same.


Yes. I usually bind the sate of my component to a property in my model.

As long as you are making the properties on your model bindable you should be able to bind directly to you model in your view. You sitl have to set the state in you model. Id look into using a framework like [swiz][http://swizframework.org/] or or mate.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜