Extending Flex Framework: Value-Aware ComboBox

What I love about Flex is that it is a framework. On top of library of the off-the-shelf controls which fits the bill for many of the Rich Internet Applications needs, Flex enables you to create new or extend existing components with a simplicity and elegance hardly ever offered by other GUI development systems. Here is an illustration of extending standard ComboBox component.How do you programmatically select a specific value in a ComboBox? Suppose the ComboBox is populated with array of states:

private var usStates:Array=[
    {label:”New York”, data:”NY”},
    {Colorado”, data:”CO”},
    {Texas”, data:”TX”}
];
. . . . . . . .
   <mx:ComboBox id=”cbx_states” dataProvider=”{usStates}”/>
To force Texas to the visible portion of the ComboBox you can write the following index-fetching loop, comparing val against the label of each element of dataProvider:

var val:String; val= ’Texas’ ;
for (var i: int = 0; i < cbx.dataProdider.length; i++) {     if ( val == cbx_states.dataProvider[i].label) {       cbx_states.selectedIndex = i;       break;   } }

Alternatively, you could look up the data of dataProvider’s elements :
var val:String; val= ‘TX’ ;
for (var i: int = 0; i < cbx.dataProdider.length; i++) {
    if ( val == cbx.dataProvider[i].data) {
      cbx_states.selectedIndex = i;
      break;
    }
}

Either way these index-fetching loops will clutter the application code instead of simple cbx_states.value=‘Texas’. But wait, there is value property: if a selected object has something in the data property, value refers to data, otherwise value refers to the label:mx.control.Alert.show(cbx_states.value); // displays ‘NY’

Alas, standard value is read-only. In the following part of the post we will turn value into a read-write property. Then index-fetching loops to modify the ComboBox selection will be history.

Let’s extend the original ComboBox so that derived class provides a special setter for the value property. The setter attempts to match the value with either data or label properties of the dataProvider. Once a match is found, it modifies the selectedIndex, which should cause the ComboBox to select the matching object:

<?xml version=”1.0″ encoding=”utf-8?>
<mx:ComboBox xmlns:mx=”http://www.adobe.com/2006/mxml” >
<mx:Script>
<![CDATA[
   public function set value(val:Object) : void {
    if ( val != null ) {
    for (var i : int = 0; i < dataProvider.length; i++) {
    if ( val == dataProvider[i].data || val == dataProvider[i].label) {
    selectedIndex = i;
    return;
    } } }
    selectedIndex = -1;
    }
 ]]>
<mx:Script>
<mx:ComboBox>

Listing 1. ComboBox.mxml – Making the value property writeable

If the ComboBox.mxml is located under the com/theriabook/controls, its test application can look as in Listing 2 below.

<?xml version=”1.0″ encoding=”utf-8″?>
<mx:Application xmlns:mx=”http://www.adobe.com/2006/mxml” xmlns:fx=”com.theriabook.controls.*”>
   <mx:ArrayCollection id=”comboData”>
       <mx:Array>
           <mx:Object label=”New York” data=”NY”/>
           <mx:Object label=”Connecticut” data=”CT”/>
           <mx:Object label=”Illinois” data=”IL”/>
       </mx:Array>
   </mx:ArrayCollection>
   <mx:Label text=”Current bound value is ‘{cbx_1.value}’ ” />
   <fx:ComboBox id=”cbx_1″ value=”IL” width=”150″ dataProvider=”{comboData}”/>
<mx:Application>

Listing 2. Using our new ComboBox

Run this application, and you’ll see the ComboBox displaying the value New York… while we would expect Illinois. We forgot about the order in which objects’ properties (cbx_1) get initialized. In particular, the value property is initialized before the dataProvider. And, since during dataProvider initialization ComboBox, by default, selects the first item, the work performed by our value setter is wasted. You can prove the point by just trading places of value and dataProvider in the above application code.

Should I rely on the order of attributes in MXML components? Apparently not. Especially when Flex offers an excellent mechanism to coordinate the updates to multiple properties of the control – the commitProperties() method.

Here is how it works: whenever you need to modify a property raise some indicator, store the value in the temporary variable and call invalidateProperties(), like in the following snippet:

 private var candidateValue:Object;
 private var valueDirty:Boolean = false;
 public function set value(val:Object) : void {
   candidateValue = val;
   valueDirty = true;
   invalidateProperties();
   }

In response to invalidateProperties() Flex will guarantee a call of commitProperties() at a later time, so that all property changes deferred in the above manner can be consolidated in a single place and in the pre-determined order:

override protected function commitProperties():void {
    super.commitProperties();      if (dataProviderDirty) {
      super.dataProvider = candidateDataProvider;
      dataProviderDirty = false;
   }

   if (valueDirty) {
      applyValue(candidateValue);
      valueDirty = false;
   }
}

Aside of co-ordinating updates to different properties, this coding pattern helps to avoid multiple updates to the same property and, in general, allows setter methods to return faster, improving the overall performance of the control. The entire code of our “value-aware” ComboBox is presented in Listing 3:

<?xml version=”1.0″ encoding=”utf-8″?>
<mx:ComboBox xmlns:mx=”http://www.adobe.com/2006/mxml”>
<mx:Script>
<![DATA[

   private var candidateValue:Object;
   private var valueDirty:Boolean = false;
   private var candidateDataProvider:Object;
   private var dataProviderDirty:Boolean = false;
   
   private function applyValue(val:Object):void {
       if ((val != null) && (dataProvider != null)) {
               
          for (var i : int = 0; i < dataProvider.length; i++) {
               if ( val == dataProvider[i].data || val == dataProvider[i].label) {
                  ;  selectedIndex = i;
                  ;  return;
       }    }    }
       selectedIndex = -1;
   }      public function set value(val:Object) : void {
       candidateValue = val;
       valueDirty = true;
       invalidateProperties();
   }
   override public function set dataProvider(value:Object):void {
       candidateDataProvider = value;
       dataProviderDirty = true;
       invalidateProperties();
   }

   override protected function commitProperties():void {
       super.commitProperties();

       if (dataProviderDirty) {
          super.dataProvider = candidateDataProvider;
          dataProviderDirty = false;
       }

       if (valueDirty) {
          applyValue(candidateValue);
          valueDirty = false;
       }
   }
   ]]>
<mx:Script>
<mx:ComboBox>

Listing 3. The value-aware ComboBox

Now everything works as expected. If you change the ComboBox selection, the top label, which initially contains Current bound value is “IL” will change accordingly. No miracles here, a regular Flex data binding one would say. Indeed, good things are easy to take for granted. Still, we have not provided any binding declarations or binding code in our ComboBox. So why does it work? It works because the original Flex definition of value getter ComboBox has already been marked with metadata tag [“Bindable”], which makes the property bindable (you do not have to have a setter to be bindable):

[Bindable(“change”)]
[Bindable(“valueCommitted”)]

But wait, you may say, these binding definitions contract us to trigger events change and valueCommitted. Yet our value setter does not contain a single dispatchEvent call. Where is the catch? Events are dispatched inside the code that assigns selectedIndex. This assignment results in invocation of selectedIndex setter, which ultimately dispatches events.

Remember, Flex is a framework.Read the code :)

Victor

7 thoughts on “Extending Flex Framework: Value-Aware ComboBox

  1. Victor,

    Your ComboBox works incorrectly in table — the initial value is not passed.
    To overcome this problem you need the following method override:
    /* A small override of “set data” in mx.controls. ComboBox */
    /* This allows to use value-aware version in DataGrid and List-s */
    override public function set data(data:Object):void {
    super.data = data;
    if (listData && listData is DataGridListData) {
    candidateValue = data[DataGridListData(listData).dataField];
    valueDirty = true;
    }
    else if (listData is ListData && ListData(listData).labelField in data) {
    candidateValue = data[ListData(listData).labelField];
    valueDirty = true;
    }
    }

    =======
    Moreover, original mx.controls.ComboBase class has small error in “get value” — as a result, you may not use ComboBox if values are Boolean (namely, Boolean(false) )
    Here is the fix:

    override public function get value():Object {
    if (editable)
    return text;

    var item:Object = selectedItem;

    if (item == null || typeof(item) != “object”)
    return item;

    return “data” in item ? item.data : item.label;
    }

    Valery

  2. Valery, thank you for the comment. You are absolutely right, but this was an introductory post just to demo expandablity of the Flex framework. We’ve addressed this issue in our book which dedicates an entire chapter to tricks with comboboxes. Did not know about Boolean, though :)

    Thank you so much again,
    Victor

  3. Should’nt all this “functionality” be already built into a combo box control? My God look at all the code i need to write to get a combo box to work just like a good old fashioned HTML dropdown. In order to set a selected value i need to write functions and in order to pass a value different than than the selectedItem I also need to write a function. RIA my ass. Did I miss the boat? Shouldnt these functions already be part of the class? .NET has all this stuff built in. Com’n Adobe/Flex team get it right. I love to think what flex “could be” but it ain’t there yet. I don’t want to re-write or extend classes to do basic functionality that should be built in.

  4. Samian, clearly you have made a fallacy of equivocation. If having to extend a framework writing a few functions is too much of a burden that is fine, but don’t imply that if Adobe had gotten the Flex combo box right then it ‘could be’ a ‘good old fashioned HTML dropdown’. I do not think that having to borrow one class and dropping it into a project is going to convince very many people that we should forfeit the whole list of benefits that a Flex combo box has to offer over a ‘good old fashioned HTML dropdown’.

    Which makes me wonder what constitutes an RIA if having to ‘write functions’ is clearly a demerit towards the seal of approval. I suppose I could dust off my old etch-a-sketch and send it on over unless of course you already have the .NET etch-a-sketch in which case you clearly already know everything there is to know.

  5. Hello Victor,
    Great post btw, it’s leading me in a good direction.

    I’m trying to get your combobox modification to do a bidirectional bind with a data model:

    public function set value(val:Object) : void {
    candidateValue = val;
    valueDirty = true;
    invalidateProperties();
    /*****************************************dispatch here
    dispatchEvent(new Event(“changeValue”));
    }

    /*****************************************bind here
    [Bindable(event=”changeValue”)]
    override public function get value():Object {
    if (editable)
    return text;

    var item:Object = selectedItem;
    if (item == null || typeof(item) != “object”){
    return item;
    }
    return “data” in item ? item.data : item.label;
    }

    however, i get the warning: ‘Data binding will not be able to detiect assignments to “value” ‘ regardless. I know the value property is available on the stock combobox, do you know of a way to make the value property bindable again? Thank you immensely.

  6. Hello Victor,

    
        private function applyValue(val:Object):void 
        {
          if ((val != null) &amp;&amp; (dataProvider != null)) 
          {
                for (var i : int = 0; i &lt; dataProvider.length; i++) 
                {
                  //Используем labelField в качестве данных,
                  //Не плохо бы добавить и labelFunction
                  if( this.labelField != null )
                  {
                    if( val == dataProvider[i][labelField] ) 
                    {
                      selectedIndex = i;
                        return;
                    }
                  } else {
                    if( val == dataProvider[i].data || val == dataProvider[i].label ) 
                    {
                      selectedIndex = i;
                        return;
                     }
                   }    
                 }
          }else{
                 selectedIndex = -1;
             }
         }
    

Comments are closed.