28 March 2011

Ext JS - Mixed Collection Extension

At the top of my wish list for Ext JS is some recursive container search logic. There are times when you need to access a control on a form and can get it via a search term.

 In this case, I wanted to look for the control with a tab index of one greater than the current control. Ext.getCmp would make one control dependent on another.  This logic enables me to find the next control in the container by searching for by property for the next largest tabIndex property.

This extension will recursively search an Ext JS (v 2.x) mixed collection for the first object that has the property you are looking for.  The new method is called 'findByProperty'.


/* Extends the mixed collection object and recursively finds an object */

Ext.override(Ext.util.MixedCollection, {

    findByProperty: function (property, value, defaultValue) {

        var obj = defaultValue,

            notFound = true,

            find = function (itm, idx, len) {

                if (itm.items) {
                    this.items.each(find);
                }

                if (itm[property] && itm[property] === value) {
                    obj = itm;
                    notFound = false;
                }

                return notFound;
            };

        this.each(find);

        return obj;
    }
});



Where:
  • property is the string property you are looking for
  • value is the property value 
  • defaultValue is the optional value to be returned if nothing is found