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

How to get filtered results with backbone.localStorage?

本文关键字:过滤 结果 获取 localStorage 何使用 backbone      更新时间:2023-09-26

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 筛选事件?

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

过滤部分可以在没有获取的情况下完成,方法是在您的商店中使用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 源代码的启发):

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/