Sorting

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 first alphabetically

The second form of comparator is a function that takes a single argument. If this form is used, Backbone will pass any Models it is trying to sort to this function one at a time and then use whatever value is returned to sort the Model. For instance, if you want to sort your Models alphabetically, except if that Model is Heathcliff, you can use a comparator of this form:

var Cats = Backbone.Collection.extend({
    comparator: function(cat) {
        if (cat.get('name') == 'Heathcliff') return '0';
        return cat.get('name'),
    }
});
var cartoonCats = new Cats([ 
    {name: 'Heathcliff'},    {name: 'Garfield'}
]);
cartoonCats.at(0); // heathcliff, because "0" comes before "garfield" alphabetically

The final form of comparator is a function that takes two Model arguments and returns a number, indicating whether the first argument should come before (-1) or after (1) the second. If there is no preference as to which Model should come first, the function will return 0. We can implement our same first Heathcliff comparator using this style:

var Cats = Backbone.Collection.extend({
    comparator: function(leftCat, rightCat) {
        // Special case sorting for Heathcliff
        if (leftCat.get('name') == 'Heathcliff') return -1;
        // Sorting rules for all other cats
        if (leftCat.get('name') > rightCat.get('name')) return 1;
        if (leftCat.get('name') < rightCat.get('name')) return -1;
        if (leftCat.get('name') == rightCat.get('name')) return 0;
    }
});
var cartoonCats = new Cats([ 
    {name: 'Heathcliff'},    {name: 'Garfield'}
]);
cartoonCats.at(0);// heathcliff, because any comparison of his name will return -1
..................Content has been hidden....................

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