在Backbone.js中有效地实现搜索

时间:2015-09-09 03:53:28

标签: javascript backbone.js

我正在尝试对我当前的集合执行搜索,如果未检索到结果,我正在尝试查询我的搜索API

收集:

  var Backbone = require('backbone'),
  _ = require('underscore'),
  Urls = require('../../libs/urls'),
  services = require('../../libs/services'),
  skuListModel = require('../../models/sku/SkuListModel');
var SkuListCollection= Backbone.Collection.extend({
  model: skuListModel,
    sync: function (method, model, options) {
    options = _.defaults({}, options, {
      readUrl: Urls.sku.list
    });

    return services.sync.call(model, method, model, options);
  }
});

查看

     searchData: function (e) {
    var self = this;

    var models = this.skuCollection.filter(function (item) {
      return item.get("sku_code").indexOf(e.target.value) > -1
    });
     console.log(models);
    if (models != null) {

      self.skuCollection.set(models);

    }
    else {
      self.skuCollection.fetch({
        data: {
          search_string: e.target.value
        }
      }).then(function (response) {
        console.log(response);
        //self.skuCollection.add(self.skuSearchCollection.toJSON(), { silent: true });
      });

    }

  }

我的问题是如何有效地修改我当前的集合以存储检索到的结果以及我的解决方案是否有效。

1 个答案:

答案 0 :(得分:1)

  1. 将过滤逻辑移至集合
  2. 使用promises来统一你的回复:如果你找到模型就会立即解决延迟,如果你需要获取数据则是xhr对象
  3. 通过set options自定义fetch的行为,例如{remove: false}以保留现有模型
  4. 这些要点导致了集合定义:

    var SkuListCollection = Backbone.Collection.extend({
        skus: function(code) {
            var self = this;
            var filtered = function() {
                return self.filter(function (item) {
                    return item.get("sku_code").indexOf(code) !== -1;
                });
            };
    
            var models = filtered();
    
            if (models.length) {
                // models found : define a promise and resolve it
                var dfd = $.Deferred();
                dfd.resolve(models);
                return dfd.promise();
            } else {
                // models missing: fetch and add them
                return this.fetch({
                    remove: false,
                    data: {
                        search_string: code
                    }
                }).then(filtered);
            }
        }
    });
    

    您的观点将重新布线为:

    searchData: function (e) {   
        this.skuCollection.skus(e.target.value).then(function(models) {
            // do what you have to do with the filtered models
        });
    }
    

    演示http://jsfiddle.net/nikoshr/84342xer/1/