Ordering methods

Finally, we have toArray, sortBy, and groupBy, all of which allow you to get an array of all the Models stored in a Collection. However, while toArray simply returns all the Models in the Collection, sortBy returns Models sorted by a provided criteria, and groupBy returns Models grouped into a further level of arrays. For example, if you want to get all the books in a Collection sorted alphabetically, you can use sortBy:

var books = new Backbone.Collection([
    {title: "Zebras Are Cool"},
    {title: "Alligators Are Also Cool"},
    {title: "Aardvarks!!"}
]);
var notAlphabeticalBooks = books.toArray();
notAlphabeticalBooks;// will contain Zebras, then Alligators, then  Aardvarks
var alphabeticalBooks = books.sortBy('title'),
alphabeticalBooks;// will contain Alligators, then Aardvarks, then Zebras

If, instead, you want to organize them into groups based on the first letter of their title, you can use groupBy, as follows:

var firstLetterGroupedBooks = books.groupBy(function(book) {
    return book.get('title')[0];
});
// will be an array of [Alligators,  Aardvarks], [Zebras]
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.119.158.134