如何使用 backbone.localStorage 获取过滤结果
How to get filtered results with backbone.localStorage?
我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/
相关文章:
- 如何在BookshelfJS中通过加入来过滤结果
- AEM/CQ应用程序:基于过滤结果的PDF生成器
- 如何根据角度中的复选框选择过滤结果
- Jquery 从选择选择的插件过滤结果
- 如何使用 backbone.localStorage 获取过滤结果
- 如何使用jquery从数据表中单击按钮时选择过滤结果
- 过滤结果以显示与ng匹配的结果显示angular js
- 仅为instagram视频过滤结果-instafeed.js
- 如何防止通过Twitter Bootstrap'过滤结果;s打字机
- 谷歌地图-基于JavaScript对象过滤结果
- AngularJS:过滤数组并访问被过滤结果中的嵌套数组
- 如何在Angular中使用复选框来过滤结果
- Symfony2过滤结果- ajax请求的问题
- 如何从 javascript 中的数组对象获取过滤结果
- 无法在控制器上访问ngRepeat的过滤结果
- JavaScript | AngularJS:根据日期过滤结果过滤项目
- 带过滤结果的Angular ng-if
- 基于IS AngularJS过滤结果
- 如何在angularjs中基于ID过滤结果
- 从javascript对象中过滤结果