Filtering a Backbone Collection returns an array of Models

15,479

Solution 1

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)

Solution 2

var collection = new Backbone.collection(yourArray)

Solution 3

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

Share:
15,479

Related videos on Youtube

Dru
Author by

Dru

Updated on June 01, 2022

Comments

  • Dru
    Dru almost 2 years

    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?

  • Daniel Ozean
    Daniel Ozean about 12 years
    Collection#refresh was renamed to Collection#reset documentcloud.github.com/backbone/#Collection-reset
  • Dmitri Zaitsev
    Dmitri Zaitsev over 10 years
    This only works for "vanilla" Backbone Collection. Even with custom Collection one would need to hard-code its definition. The solution above with reset nicely avoids that.