Google News
logo
Backbone - Interview Questions
How can you sort a collection? When is it important to explicitly invoke "sort()" on a collection?
In Backbone.js, by default, collections are not explicitly sorted. We can sort the collections by defining a comparator on the collection object. By defining a comparator, a collection is sorted whenever a model is added or the "sort()" method is invoked on a collection :
 
Example :
var Fruits = Backbone.Collection.extend({  
    comparator: function(a, b) { /* .. */ }  
})  
// Or  
var Fruits = Backbone.Collection.extend({})  
var fruits = new Fruits()  
fruits.comparator = function(a, b) { /* .. */ }  
 
The comparator property can be a function with one argument or two arguments (similarly used in "sort"), or a string identifying the attribute by name to sort on.
 
When an attribute of a model in a collection changes, the collection doesn't sort itself. In this case, the sort must be invoked explicitly to update the order of models in the collection.
Advertisement