过滤骨干集合返回模型数组

发布于 2024-11-16 10:47:34 字数 648 浏览 2 评论 0原文

示例代码:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

大姐,你呐 2024-11-23 10:47:35

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

var myPublishedBooks = new MyBooksCollection(publishedBooks);

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

this.books.refresh(publishedBooks)

请注意2011 年 7 月发布的 0.5.0 已重命名为 refreshreset,这样您就可以在较新版本的 Backbone 中实现此目的:

this.books.reset(publishedBooks)

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)

Note that the 0.5.0 release in July 2011 renamed refresh to reset, so you can achieve this in newer versions of Backbone with;

this.books.reset(publishedBooks)
指尖凝香 2024-11-23 10:47:35
var collection = new Backbone.collection(yourArray)
var collection = new Backbone.collection(yourArray)
思念绕指尖 2024-11-23 10:47:35

我经常做这样的事情:

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

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

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文