I’m new to Flex/Actionscript and have a very basic question.
Let’s say I have about 100+ buttons. They all have the same label. Now I want to change the label for all with a click. I could give them IDs and then run a for loop, but I’m searching for a neater solution.
Thanks for help.
Update:
Hm, it doesn’t work because label of buttons are modified during the run time.
This is the code
public function changeButton(event:Event):void {
if (event.target.label != 'X') {
event.target.label ='X';
} else {
event.target.label ='';
}
}
Now I need a button that will on click delete/replace this label with an empty one.
Off the top of my head I can offer you several solutions, depending on your definition of ‘neat’. I guess the ‘neatest’ would be dispatching an event. But I will outline all three:
1.Have label itself be an event dispatcher or some object that can notify whatever “is labelled” with its particular value. This can be seen as a variation of solution #3 of course, but is NOT. Your buttons will register listeners on the label they are assigned, and by making the label change operation dispatch a change event your buttons will have a chance to update their label display. This is neat because you can have a reusable generic programming pattern along:
2.Another one, like what you thought of but thought was not neat enough, which I assume would be faster to update is keeping a track of buttons with the same label in a container that is easily iteratable, e.g. a dictionary (need weak keys, so a vector won’t do!)
3.Use the benefits of display list hierarchy and the event flow model to have Flash Player do most of the work for you:
What I suggest you do is examine the weaknesses and strengths of each – all of them DO have both – and use a hybrid solution. The first has the effect of separating the value of a label with a reference to the value, i.e. two different label objects both with “Cancel” as value will NOT change each other, even though the label is actually identical. The other two solutions don’t separate value from reference. With them however you get the extra cost of adding too many event listeners with too many buttons, something the second solution does not do. This all was off the top of my head, but you have an interesting problem, use your fantasy now 🙂