Sorting a collection
Sorting a collection is fairly easy with Backbone as built-in methods are already available for this purpose. To sort a collection, add a comparator
to the collection, which in general, is a function that can take a single model or two consecutive models for comparison, or it can be a string that points to an attribute of its model. Whenever a model is added to the collection, the comparator sorts the collection accordingly. Changing an attribute of a model later doesn't initiate the sort functionality automatically and you need to call the sort()
method on the collection again to re-sort it. Let's look into a simple example of sorting a collection:
var User = Backbone.Model.extend(); var Users = Backbone.Collection.extend({ model: User, comparator: 'age' }); var users = new Users(); users.add([{ name: 'John Doe', age: 29 }, { name: 'Richard Smith', age: 35 }, { name: 'Swarnendu De', age: 29 }, { name: 'Emily Johnson', age: 25 }, { name: 'Sarah...