Backbone can automatically sort all Models
added to a Collection
if you tell it to by specifying a comparator. As with a model, a Collection's comparator can be provided as an option when the Collection
class is created:
var Cats = Backbone.Collection.extend({comparator: 'name'}); var cartoonCats = new Cats(); cartoonCats.comparator; // 'name'
While the provided comparator controls how the Collection sorts its models internally, you can also sort a Collection using alternate comparators by using one of Underscore's sorting methods, which we'll detail at the end of the chapter.
The comparator itself can come in three forms. The first and simplest form is the name of an attribute of the Models in the Collection. If this form is used, Backbone will sort the collection based on the values of the specified attribute:
var cartoonCats = new Backbone.Collection([ {name: 'Heathcliff'}, {name: 'Garfield'} ], { comparator: 'name' }); cartoonCats.at(0);// garfield, because his name sorts...