views:

265

answers:

2

I have this bit of code, and it's not working as I expected. btnContainer is a VBox that contains a ton of buttons (toggle=true); and I want to reset them to un-toggled at a certain point.

for (var btn:Object in btnContainer.getChildren()){
    if (btn.isPrototypeOf(mx.controls.Button)){
     btn.selected = false;
    }
}

With the above code, "btn" shows up as just the index during each iteration of the loop (0,1,2,3,...), and the conditional never evaluates to true.

I also tried this:

for (var btn:Button in btnContainer.getChildren()){
    btn.selected = false;
}

This works fine, except that there is also a label inside btnContainer; so it throws an error when trying to cast the label as a button.

What am I doing wrong, here?

+2  A: 

Have you tried using "is"?

import mx.controls.Button;

//...
for (var key in btnContainer.getChildren() ){
    var obj : Object = btnContainer[key];
    if (obj is Button){
        var button : Button = obj as Button;
        button.selected = false;
    }
}

Michael Aaron Safyan
+3  A: 

If you want to loop through the elements of an array, use a "for each..in" loop, and if you want to see if a variable is compatible with a given type (e.g. an instance of a given class), use the is operator.

The language reference has an example for this exact kind of case.

Here's the fixed code:

for each (var btn:Object in btnContainer.getChildren()){
    if (btn is Button){
        btn.selected = false;
    }
}
hasseg
Ah, I had dropped the "each" part because I had a brain fart and thought it was optional. Make's sense, thanks.
Adam Tuttle
without the "each" it means something different: it will iterate over the properties of the element, a sort of type introspection (could be useful sometimes).
Cosma Colanicchia