如何使用 Backbone.js 将过滤后的集合转换为 JSON?
所以我在 Backbone 中有一个事件列表的集合。该集合有一个方法,可以根据传递给它的类别列表来过滤列表。
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,就像处理整个集合一样。
var events = new Events();
events.toJSON();
但是,由于过滤后的集合不再是实际的集合,而是模型列表,因此我没有可用的 .toJSON() 方法。有没有办法将我的过滤集合转换为真实集合?或者有没有更简单的方法将其转换为 JSON?
谢谢!
So I have a collection in Backbone for a list of events. This collection has a method on it which filters the list based on a list of categories passed to it.
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;
}
});
}
});
What I need to be able to do is convert this filtered collection to JSON, the same way you would do the collection as a whole.
var events = new Events();
events.toJSON();
However, because the filtered collection is no longer an actual collection, but rather a list of models, I don't have the .toJSON() method available to me. Is there a way to convert my filtered collection to a real collection? Or is there an easier way to convert it to JSON?
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
集合的构造函数可以将模型列表作为参数,因此:
The constructor for a collection can take a list of models as an argument so:
为什么不使用标准 API?
另外,
Events.filterByCategoryName
方法名称更加明确。然而,我倾向于不在设计中实现太多“方便”的方法,而是直接使用它们来拥抱标准 API。Why not make use of the standard API?
On a separate note,
Events.filterByCategoryName
method name is more explicit. However, I tend not to implement too many 'convenient' methods in my design and embrace the standard API by using them directly.您还可以尝试以下操作:
从内到外开始:
You could also try something like:
Starting from the inside out:
你可以这样做:
You can do like so :
我解决这个问题的方法是在集合上运行一个
reduce
函数。这样做的优点是,您只需对集合本身执行 1 次传递,仅记住有效的模型,并在通过验证时返回模型的 JSON。其他用于构建新集合的解决方案在性能方面非常糟糕。
The way I solved it is running a
reduce
function on the collection. The advantage of this is that you only do a 1 pass on the collection itself, remembering only the valid models, and returning the JSON of the model if they pass validation.The other solutions offered to build a new collection which is performance wise - terrible.