Accessing values across components in Flex
I am working and see an email come in from flexcoders asking how you would access a variables value in one component from another. Easy enough. Well, that is what I thought. I came up with three different answers to this problem and I am convinced there are others. All good enough, but which is best to implement. I will let you decide.
1. Put bindable public variables (properties) on your components and set the values in the parent.
2. Dispatch an event on one component and have the parent component set the other components property.
3. Create a singleton class that holds the values and bind the data to your components, so when there is a change, the values in the components will be set accordingly.
I like the third answer best, but is a bit overkill for the simple implementation that does not need to access the information more than once. The third has more scalability, but takes longer to code.
Demo Example
Source Code
Which would you use? I think it is based on your needs.
1 comments:
I'm inclined with the second of your options. It has the virtues of:
1) Not replicating information throughout the application. In the third option, you have the same information in the singleton and the view.
2) If you come back and decide that additional items are dependent on that value, or the state of that value, the event model will be more obliging.
3) If you need to perform other actions, instead of simple binding, the event model is the way to go.
(Maybe 2 and 3 are the same thing, actually)
Post a Comment