过滤骨干集合返回模型数组
示例代码:
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
但我仍然可以不要运行这样的事情: PublicationBooks.each(...),或 publishedBooks.get(...)
我错过了什么?有没有办法将返回的数组转换为集合?
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:
var publishedBooks = _( this.books.filter(function(book) {
return book.get("isPublished") === "1";
}))
as recommended by this post:
https://github.com/documentcloud/backbone/issues/120
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以实例化一个新的骨干集合并传入数组。
或者您可以刷新您的原始收藏。
请注意,2011 年 7 月发布的 0.5.0 已重命名为
refresh
到reset
,这样您就可以在较新版本的 Backbone 中实现此目的:You could either instantiate a new backbone collection and pass in the array.
Or you could refresh your original collection.
Note that the 0.5.0 release in July 2011 renamed
refresh
toreset
, so you can achieve this in newer versions of Backbone with;我经常做这样的事情:
这将创建一个与原始集合类型相同的实例,其中包含过滤后的模型,因此您可以继续使用集合方法(each、filter、find、pluck 等)。
I often do something like this:
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).