В принципе, вы хотите отфильтровать модели, хранящиеся в локальном хранилище, при получении вашей коллекции.
Фильтрующая часть может быть сделано без выборки, с помощью 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/
Спасибо за лучший ответ! – Erik