在下面的代码中,我设置了一个视图,我根据日期输入过滤集合。代码第一次正常工作,但显然集合重置,然后如果我再次按日期过滤它不会从原始集合中过滤。过滤骨干中的集合并维护原始副本的最佳做法是什么?
window.DataIndexView = Backbone.View.extend({
tagName: 'section',
className: 'data',
events: {
"click #changedate" : "filterDate"
},
initialize: function(){
_.bindAll(this, 'render', 'filterDate');
.template = _.template($("#data_template").html());
this.collection.bind('reset', this.render());
},
render: function(){
var data = this.collection;
$(this.el).html(this.template({}));
data.each(function(point){
});
return this;
},
filterDate: function() {
var startdate = this.$("#startdate").val();
var filtered = _.filter(this.collection, function(item) {
return moment(item.get("date")).valueOf() > moment(startdate, 'MM-DD-YYYY').valueOf();
});
this.collection.reset(filtered);
}
});
答案 0 :(得分:0)
_。过滤不会触摸您的收藏。它返回一个全新的阵列。如果愿意,您可以使用它来实例化新的集合。
我相信你想要的东西可以通过像
这样的东西来实现filterDate: function() {
var startdate = this.$("#startdate").val();
// Basically a collection clone. It'll keep the same references,
// instead of copying each object
this.original_collection = new YourCollectionType(this.collection.models);
this.collection.reset(_.filter(this.collection, function(item) {
return moment(item.get("date")).valueOf() > moment(startdate, 'MM-DD-YYYY').valueOf();
}));
// Render triggered automagically.
}
答案 1 :(得分:0)
您不应在视图中过滤您的收藏。更好的方法是从原始集合创建FilteredCollection。
function DateFilteredCollection(original){
var filtered = new original.constructor();
filtered.filter = function(startdate){
var filteredItems = _.filter(this.collection, function(item) {
return moment(item.get("date")).valueOf() > moment(startdate, 'MM-DD-YYYY').valueOf();
});
filtered.reset(filteredItems);
};
original.on('reset', function(){
filtered.reset(original.models);
});
return filtered;
}
window.DataIndexView = Backbone.View.extend({
tagName: 'section',
className: 'data',
events: {
"click #changedate" : "filterDate"
},
initialize: function(){
_.bindAll(this, 'render', 'filterDate');
.template = _.template($("#data_template").html());
this.collection.bind('reset', this.render());
},
render: function(){
var data = this.collection;
$(this.el).html(this.template({}));
data.each(function(point){
});
return this;
},
filterDate: function() {
var startdate = this.$("#startdate").val();
this.collection.filter(startdate); // use filter function here
}
});
var original = new OriginalCollection(); // your original collection
var filteredCollection = DateFilteredCollection( original );
var dataIndexView = new window.DataIndexView({
collection: filteredCollection
});
original.fetch(); // fetch the data -> filteredCollection will automatically filter it.