繁体   English   中英

IgnoreCase bone.js集合?

[英]IgnoreCase backbone.js collection?

我一直在尝试使用collection.where在骨架.js集合上执行不区分大小写的搜索,我只是意识到,集合中搜索值和模型字段值的大小写必须匹配。 我找到了这个示例,但是在哪里可以覆盖行为或有替代方法? 谢谢

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

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

//仅在字符串大小写匹配时起作用。

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();
        });
     }  

});

我选择覆盖集合中的where和findWhere,以允许caseInsensitive选项:

  //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);
  }

并通过以下方式调用:

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

它不是很漂亮,但原始实现也不是。 O_O

将其作为拉取请求打开也很好,但是可以将where函数中的“ first”变量重构为选项的关键。 这是我要做的事情。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM