Javascript 过滤主干集合将返回模型数组

Javascript 过滤主干集合将返回模型数组,javascript,collections,backbone.js,underscore.js,Javascript,Collections,Backbone.js,Underscore.js,示例代码: this.books = this.getBooksFromDatabase(); this.publishedBooks = this.books.filter(function(book) { return book.get("isPublished") === "1"; }); 问题在于: this.books.filter返回一个模型数组。我已尝试将数组包装为: var publishedBooks = _( this.books.filter(function(boo

示例代码:

this.books = this.getBooksFromDatabase();
this.publishedBooks = this.books.filter(function(book) {
  return book.get("isPublished") === "1";
});
问题在于:

this.books.filter返回一个模型数组。我已尝试将数组包装为:

var publishedBooks = _( this.books.filter(function(book) {
  return book.get("isPublished") === "1";
}))
根据这篇文章的建议:

但我仍然无法处理以下事情: 已发布书籍。每个(…),或 publishedBooks.get(…)


我错过了什么?有没有办法将返回的数组转换为集合?

您可以实例化一个新的主干集合并传入数组

var myPublishedBooks = new MyBooksCollection(publishedBooks);
或者你可以刷新你的原始收藏

this.books.refresh(publishedBooks)

注意重命名后的
刷新
重置
,因此您可以在较新版本的主干网中实现这一点

this.books.reset(publishedBooks)

我经常这样做:

var collection = new MySpecialCollection([...]);
//And later...
var subset = new collection.constructor(collection.filter(...));
这将使用过滤模型创建与原始集合类型相同的实例,因此您可以继续使用集合方法(每个、筛选、查找、清除等)。

collection#refresh已重命名为collection#reset此方法仅适用于“香草”主干集合。即使使用自定义集合,也需要对其定义进行硬编码。上面的重置解决方案很好地避免了这种情况。
var collection = new MySpecialCollection([...]);
//And later...
var subset = new collection.constructor(collection.filter(...));