Filtering a Backbone Collection returns an array of Models

前端 未结 3 560
终归单人心
终归单人心 2021-01-03 19:27

Sample Code:

this.books = this.getBooksFromDatabase();
this.publishedBooks = this.books.filter(function(book) {
  return book.get(\"isPublished\") === \"1\";         


        
相关标签:
3条回答
  • 2021-01-03 20:23
    var collection = new Backbone.collection(yourArray)
    
    0 讨论(0)
  • 2021-01-03 20:26

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

    0 讨论(0)
  • 2021-01-03 20:29

    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)
    
    0 讨论(0)
提交回复
热议问题