javascript 过滤一个主干集合返回一个模型数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6414976/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Filtering a Backbone Collection returns an array of Models
提问by Dru
Sample Code:
示例代码:
this.books = this.getBooksFromDatabase();
this.publishedBooks = this.books.filter(function(book) {
return book.get("isPublished") === "1";
});
Here lies the problem:
问题就在这里:
this.books.filter, returns an array of the models. I've tried wrapping the array, as such:
this.books.filter,返回一个模型数组。我试过包装数组,如下所示:
var publishedBooks = _( this.books.filter(function(book) {
return book.get("isPublished") === "1";
}))
as recommended by this post: https://github.com/documentcloud/backbone/issues/120
正如这篇文章所推荐的:https: //github.com/documentcloud/backbone/issues/120
But i still can't run things like: publishedBooks.each(...), or publishedBooks.get(...)
但我仍然无法运行诸如:publishedBooks.each(...) 或publishedBooks.get(...)
What am I missing? Is there a way to convert the returned array into a collection?
我错过了什么?有没有办法将返回的数组转换为集合?
回答by c3rin
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)
Notethat the 0.5.0 release in July 2011renamed refresh
to reset
, so you can achieve this in newer versions of Backbone with;
请注意,2011 年 7 月的0.5.0 版本重命名refresh
为reset
,因此您可以在较新版本的 Backbone 中实现这一点;
this.books.reset(publishedBooks)
回答by Andrea Puddu
var collection = new Backbone.collection(yourArray)
回答by stephenr85
I often do something like this:
我经常做这样的事情:
var collection = new MySpecialCollection([...]);
//And later...
var subset = new collection.constructor(collection.filter(...));
This will create an instance of the same type as your original collection, with the filtered models, so you can continue with the collection methods (each, filter, find, pluck, etc).
这将使用过滤模型创建与原始集合相同类型的实例,因此您可以继续使用集合方法(each、filter、find、pluck 等)。