Flex: Is there a way to bind ComboBox's selectedItem to a variable?

21,468

Solution 1

Yes, ComboBox's selectedItem property is bindable.

It would go something like this:

<mx:ComboBox selectedItem="{mySelectedItem}">
</mx:ComboBox>

In your AS:

[Bindable]
var mySelectedItem:Object;

Changes to mySelectedItem should show up in ComboBox. You may get errors if the item referenced by mySelectedItem does not exist in the ComboBox's dataProvider.

Solution 2

On the surface, it's as simple as:

<mx:ComboBox id="myComboBox"
   dataProvider="{myDataProvider}"
   selectedItem="{defaultItem}"/> 

When you set defaultItem (make sure it is [Bindable]) to one of the items in the data provider, it will update the control.

But there are problems with this approach. Unless currentDefaultItem always changes AFTER myDataProvider, the binding to dataProvider may undo the selection, reverting to the default (first item in the list).

One way around this is to force selectedItem to be rebound after dataProvider, by including dataProvider in the call providing the selectedItem.

<mx:ComboBox id="myComboBox"
   dataProvider="{myDataProvider}"
   selectedItem="{getSelectedItem(myComboBox.dataProvider, defaultItem)}"/>

What this does is ensure selectedItem will be rebound when either currentDefaultItem changes, or after the dataProvider changes. I'd be interested in other solutions myself.

Solution 3

Use an event listener for the Change event and do your processing there.

// update a label item's text with that of the Combobox's selectedItem
private function changeEvt(event:Event):void {
    label.text =event.currentTarget.selectedItem.label + " " + 
}

Solution 4

or, you could do something like this if you don't mind extending ComboBox; This is pseudocode (sorry, identification of matches depends on the object type) - but you get the idea...

public class IndexRetainingComboBox extends ComboBox 
{
    public function IndexRetainingComboBox()
    {
        super();
    }

    override public function set dataProvider(value:Object):void
    {
        var originalSelection:Object = this.selectedItem;
        super.dataProvider = value;
        var newIdx:uint = [find originalSelection idx in combobox or return 0 ]
        this.selectedIndex = newIdx;
    }
}
Share:
21,468
JD Isaacks
Author by

JD Isaacks

Author of Learn JavaScript Next github/jisaacks twitter/jisaacks jisaacks.com

Updated on September 01, 2020

Comments

  • JD Isaacks
    JD Isaacks almost 4 years

    OK I have a ComboBox, the dataProvider is an array of objects with label properties that give the ComboBox the list of options.

    Is there a way I can have a variable like mySelectedItem, and bind the ComboBox's selectedItem to it so that if it changes, the ComboBox's selectedItem will change to whatever it is?

    I hope this makes sense.

    Thanks!