ExtJS Combo, findRecord, and equality

ExtJS’ implementation of a combo box, ComboBox, is one of the more complicated components provided in all of ExtJS. It glues together TriggerField and DataView to allow for quite a few different uses. If you’re using both a nameField and a valueField, upon setValue a call is placed to findRecord to determine if there’s a proper display value available. findRecord is included from ExtJS 3.2.0 below:

    // private
    findRecord : function(prop, value){
        var record;
        if(this.store.getCount() > 0){
            this.store.each(function(r){
                if(r.data[prop] == value){
                    record = r;
                    return false;
                }
            });
        }
        return record;
    },

Notice the usage of the normal equality operator. In JavaScript, type coercion happens behind the scenes when using double equal. Often for Combo, that’s what you’d want. For example, if setValue is called with “51″ and the store record has an id field which is the integer 51, in JavaScript “51″ == 51.

Unfortunately, I have an application where I am sending back the integer 0 and in my store I have a record with an id of “” and another with an id of 0. With type coercion, 0 == “”, meaning only one of the two records can ever be selected, even though both will appear in the combo list.

Naturally, my resolution was to introduce triple equality, ===, to the findRecord function via Ext.override. Of course, when using the SuperSelectBox ux, I had forgotten that it splits setValue upon a delimiter, meaning findRecord is matching a bunch of strings with === and not coercing them to match my integer record ids.

Can’t have it both ways.

I’ll have to add my override to my particular extension of ComboBox that I use most places and leave the original setValue pristine.

Commenter Brian Peiris explains away the coercion confusion.

We can demonstrate JavaScript’s boolean coercion with a double NOT (!!) operator:

!!undefined === false
!!null === false
!!0 === false
!!” === false

Always valuable to remember!

Post a Comment

Your email is never shared. Required fields are marked *

*
*