2

I have been trying to execute a case insensitive search on backbone.js collection using collection.where, I just realized that the cases of the search value and the model field value in the collection have to match. I found this example but where do I override the behaviour or is there an alternative? thanks

collection.findWhere({ 'Fname': val })

and

collection.where({ 'Fname': val })

// only work when the strings cases match.

Community
  • 1
  • 1
Neo
  • 717
  • 2
  • 11
  • 26

2 Answers2

3
var myCollection = Backbone.Collection.extend({

    // define your own case insensitive where implemented using .filter
    iwhere : function( key, val ){
        return this.filter( function( item ){
            return item.get( key ).toLowerCase() === val.toLowerCase();
        });
     }  

});
pawel
  • 35,827
  • 7
  • 56
  • 53
1

I chose to override where and findWhere on my collections to allow for a caseInsensitive option:

  //case-insensitive where
  where: function(attrs, first, options){
    options = options || {};

    if (_.isEmpty(attrs)) return first ? void 0 : [];

    return this[first ? 'find' : 'filter'](function(model) {
      for (var key in attrs) {
        if (options.caseInsensitive) {
          if (attrs[key].toLowerCase() !== model.get(key).toLowerCase()) return false;
        } else {
          if (attrs[key] !== model.get(key)) return false;
        }
      }

      return true;
    });
  },

  findWhere: function(attrs, options) {
    return this.where(attrs, true, options);
  }

And call it by:

collection.findWhere({username: "AwEsOmE"}, {caseInsensitive: true});

Its not exactly pretty, but neither is the original implementation. O_o

It would also be great to open this as a pull request, but refactor the 'first' variable in the where function to be key in options. It's on my list of things to do.

BananaNeil
  • 10,322
  • 7
  • 46
  • 66
  • Nice solution, thanks; although I think calling the option `ignoreCase` is more succinct. :-) – Ben Aug 20 '14 at 12:48