筛选骨干集合将返回一个模型数组

Filtering a Backbone Collection returns an array of Models

本文关键字:一个 模型 数组 集合 返回 筛选      更新时间:2023-09-26

示例代码:

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";
}))

如本帖所推荐:https://github.com/documentcloud/backbone/issues/120

但我仍然无法运行以下内容:publishedBooks.each(…),或publishedBooks.get(…)

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

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

var myPublishedBooks = new MyBooksCollection(publishedBooks);

或者你可以刷新你的原始收藏。

this.books.refresh(publishedBooks)

请注意2011年7月的0.5.0版本将refresh重命名为reset,因此您可以在较新版本的Backbone中使用;

this.books.reset(publishedBooks)
var collection = new Backbone.collection(yourArray)

我经常做这样的事情:

var collection = new MySpecialCollection([...]);
//And later...
var subset = new collection.constructor(collection.filter(...));

这将创建一个与原始集合类型相同的实例,其中包含已筛选的模型,因此您可以继续使用集合方法(each、filter、find、pull等)。