Javascript 如何使用Backbone.js将过滤后的集合转换为JSON?
因此,我在主干中收集了一系列事件。此集合上有一个方法,该方法根据传递给它的类别列表过滤列表Javascript 如何使用Backbone.js将过滤后的集合转换为JSON?,javascript,backbone.js,Javascript,Backbone.js,因此,我在主干中收集了一系列事件。此集合上有一个方法,该方法根据传递给它的类别列表过滤列表 var Events = Backbone.Collection.extend({ model: Event, url: settings.events_url, filtered: function(checked) { return this.filter(function(e) { if ($.inArray(e.get('catego
var Events = Backbone.Collection.extend({
model: Event,
url: settings.events_url,
filtered: function(checked) {
return this.filter(function(e) {
if ($.inArray(e.get('category').name, checked) >= 0) {
return true;
} else {
return false;
}
});
}
});
我需要能够做的是将这个过滤后的集合转换为JSON,就像您将整个集合转换为JSON一样
var events = new Events();
events.toJSON();
但是,由于过滤后的集合不再是一个实际的集合,而是一个模型列表,因此我没有可用的.toJSON()方法。有没有办法将过滤后的集合转换为真实集合?还是有更简单的方法将其转换为JSON
谢谢 可以将模型列表作为参数,以便:
var events = new Events();
var filteredEvents = new Events(events.filtered(true));
console.log(filteredEvents.toJSON());
您可以这样做:
var myFilteredCollection = new Events();
_.each(myFilteredData, function(eventModel){
myFilteredCollection.add(eventModel);
});
myFilteredCollection.toJSON();
为什么不使用标准API
var checked=['foo','bar','baz'],
过滤=事件集合
.chain()
.过滤器(功能(型号){
返回u.include(选中,model.get('category').name);
})
.invoke('toJSON')
.value();
另请注意,
Events.filterByCategoryName
方法名称更为明确。但是,我倾向于在设计中不实现太多“方便”的方法,而是直接使用标准API。您也可以尝试以下方法:
filtered: function(checked) {
return _.map(this.filter(function(e) {
return $.inArray(e.get('category').name, checked) >= 0
}), function(model) {
return model.toJSON();
});
}
从里到外:
我解决这个问题的方法是在集合上运行
reduce
函数。这样做的好处是,您只需对集合本身进行1次传递,只记住有效的模型,并在通过验证时返回模型的JSON
提供的其他解决方案用于构建一个新的集合,该集合在性能方面非常糟糕
getValidItems: function () {
//return only valid items as json
return this.collection.reduce(function (validItems, row) {
if (row.isValid()) {
validItems.push(row.toJSON());
}
return validItems;
}, []);
},
//somewhere where you save
save: function() {
var validItems = this.getValidItems();
//do something with valid items
}
对解决方案的赞誉