谷歌喜欢搜索骨干收集



我希望能够搜索 backbonejs 集合中包含的模型属性。 这就是我现在的做法...

wherePartial: function(attrs) {
      // this method is really only tolerant of string values.  you can't do partial
      // matches on objects, but you can compare a list of strings. If you send it a list
      // of values; attrs={keyA:[1,2,3],keyB:1}, etc the code will loop through the entire
      // attrs obj and look for a match. strings are partially matched and if a list is found
      // it's expected that it contains a list of string values.  The string values should be considered
      // to be like an OR operation in a query.  Non-list items are like an AND.
        if (_.isEmpty(attrs)) return [];
        var matchFound = false;
        return this.filter(function(model) {
          // this is in the outer for loop so that a function isn't created on each iteration
          function listComparator(value, index, list){
            return model.get(key).toLowerCase().indexOf(value.toLowerCase()) >= 0;
          }
          for (var key in attrs) {
            if (_.isArray(attrs[key])){
              matchFound = _.any(attrs[key],listComparator);
              if (matchFound !== true) return false;
            } else {
              matchFound = model.get(key).toLowerCase().indexOf(attrs[key].toLowerCase()) >= 0;
              if (matchFound === false) return false;
            }
          }
          return true;
        });
      }

假设"C"是一个实例化的集合,这就是我使用它的方式:

姓名:乔(昵称:乔酷 昵称:乔伊(

键入到文本框中并转换为以下内容:

C.wherePartial({name:"joe",昵称:["joe the man","joe cool","joey"]}(

上述方法返回名称为 joe 的所有模型,以及该范围内具有名称 joe 的任何模型和任何昵称。 它适用于我使用它的目的。 但是,我真的很想进行不需要键:值模式的搜索。 我想在搜索框中执行此操作,就像在网络上使用搜索引擎时一样。 我考虑过只查看每个模型上的每个属性,但是当您有一个大型集合(160k+ 模型(时,这需要一段时间。

过去有没有人遇到过这样的需求? 如果是这样,你是如何解决的? 我想保留客户端上的搜索,并且不使用任何对后端的 ajax 调用。 原因是整个集合已加载到客户端上。

我想到了一个办法。 在模型实例化期间将属性序列化为字符串。 侦听更新并更新序列化。

serializeAttr: function(){
 this.serializedAttr = "";
 var self = this;
 _.each(this.toJSON(),function(value, key, list){
   self.serializedAttr += value;
 });
}

然后我可以对该缓存值进行简单的搜索:

cc.serializedAttr.toLowerCase((.indexOf("joe"(>= 0

最新更新