如何使用backbone.localStorage获取过滤结果?

时间:2014-12-14 21:55:04

标签: javascript backbone.js local-storage

我有events集合,其中包含以下文档:

{
   _id: ObjectId,
   title: 'Untitled',
   date: '01.01.2014'
}

我正在执行以下fetch查询/events/01.01.2014

var Collection = Backbone.Collection.extend({
      localStorage: new Backbone.LocalStorage("events"),

      initialize: function () {
         this.fetch({
             url: '/events/01.01.2015'             
         })
      }
});

这里的问题是集合返回所有事件而不是特定数据(如上例中的/01.01.2014)。我如何使用Backbone.LocalStorage过滤事件?

1 个答案:

答案 0 :(得分:1)

基本上,您希望在提取集合时过滤存储在本地存储中的模型。

通过在商店中使用findAll,可以在不进行提取的情况下完成过滤部分:

var c = new Collection();  // your collection, filled elsewhere
var store = c.localStorage; // associated localstorage
var allmodels = store.findAll(); // direct acces to the models in storage

// models having a matching date
var filtered = _.where(allmodels , {date: '01.01.2014'});

要在fetch之后过滤结果,您可以覆盖Collection.sync(受Backbone.localStorage's source code的启发):

var Collection = Backbone.Collection.extend({
    localStorage: new Backbone.LocalStorage("events"),

    sync: function(method, coll, opts) {
        var parentsync = Backbone.Collection.prototype.sync;
        opts = opts || {};

        // we're only interested in the fetch requests with a custom url
        if ((method !== "read") || (!opts.url))
            return parentsync.call(this, method, coll, opts);

        // let's pick the date in the url
        var re = /^\/events\/(\d{2}\.\d{2}\.\d{4})$/,
            matches = opts.url.match(re),
            date = matches && matches[1];

        // no date, no override
        if (!date)
            return parentsync.call(this, method, coll, opts);

        // the filtering described above
        var store = this.localStorage, dfd = Backbone.$.Deferred(),
            models = store.findAll();

        models = _.where(models, {date: date});

        // calling the callback and resolving the deferred
        opts.success(models);
        dfd.resolve(models);

        return dfd.promise();
    }
});

演示http://jsfiddle.net/nikoshr/0tyrk73s/