2011-06-20 33 views
25

示例代码:过滤骨干集合返回模型的数组

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(...)

我在想什么?有没有办法将返回的数组转换为集合?

回答

34

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

var myPublishedBooks = new MyBooksCollection(publishedBooks); 

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

this.books.refresh(publishedBooks) 

注意0.5.0 release in July 2011改名refreshreset,这样你就可以在骨干网的新版本实现这一点;

this.books.reset(publishedBooks) 
+12

Collection#refresh已重命名为Collection#reset http://documentcloud.github.com/backbone/#Collection-reset –

4
var collection = new Backbone.collection(yourArray) 
+0

这只适用于“香草”Backbone Collection。即使使用自定义集合,也需要对其定义进行硬编码。上面的解决方案很好地避免了这一点。 –

3

我经常做这样的事情:

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

这将创建同一类型的实例作为你的原来的集合,用过滤的模型,这样你就可以收集继续方法(每个过滤器,查找,采摘等)。