【问题标题】:Filtering a Backbone Collection returns an array of Models过滤主干集合返回一个模型数组
【发布时间】:2011-09-18 21:19:45
【问题描述】:

示例代码:

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

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

【问题讨论】:

    标签: javascript collections backbone.js underscore.js


    【解决方案1】:

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

    var myPublishedBooks = new MyBooksCollection(publishedBooks);
    

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

    this.books.refresh(publishedBooks)
    

    注意 0.5.0 release in July 2011refresh 重命名为 reset,因此您可以在较新版本的 Backbone 中实现这一点;

    this.books.reset(publishedBooks)
    

    【讨论】:

    【解决方案2】:
    var collection = new Backbone.collection(yourArray)
    

    【讨论】:

    • 这仅适用于“香草”骨干集合。即使使用自定义集合,也需要对其定义进行硬编码。上面带有重置的解决方案很好地避免了这种情况。
    【解决方案3】:

    我经常这样做:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-09-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多