过滤一个主干集合返回一个模型数组 [英] Filtering a Backbone Collection returns an array of Models
问题描述
示例代码:
this.books = this.getBooksFromDatabase();
this.publishedBooks = this.books.filter(function(book) {
return book.get("isPublished") === "1";
});
问题就在这里:
this.books.filter,返回一个模型数组.我试过包装数组,如下所示:
this.books.filter, returns an array of the models. I've tried wrapping the array, as such:
var publishedBooks = _( this.books.filter(function(book) {
return book.get("isPublished") === "1";
}))
正如这篇文章所推荐的:https://github.com/documentcloud/backbone/issues/120
as recommended by this post: https://github.com/documentcloud/backbone/issues/120
但我仍然无法运行以下内容:已出版Books.each(...),或已出版Books.get(...)
But i still can't run things like: publishedBooks.each(...), or publishedBooks.get(...)
我错过了什么?有没有办法将返回的数组转换为集合?
What am I missing? Is there a way to convert the returned array into a collection?
推荐答案
您可以实例化一个新的主干集合并传入数组.
You could either instantiate a new backbone collection and pass in the array.
var myPublishedBooks = new MyBooksCollection(publishedBooks);
或者您可以刷新您的原始收藏.
Or you could refresh your original collection.
this.books.refresh(publishedBooks)
<小时>
注意2011 年 7 月发布的 0.5.0 更名为 refresh
到 reset
,这样你就可以在新版本的 Backbone 中使用;
Note that the 0.5.0 release in July 2011 renamed refresh
to reset
, so you can achieve this in newer versions of Backbone with;
this.books.reset(publishedBooks)
这篇关于过滤一个主干集合返回一个模型数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!