Backbone.js
provides a sorting mechanism, out of the box, which we are going to learn in this recipe.
Follow these steps to sort a collection:
Assign the
comparator
callback to thecomparator
property of a collection to maintain the correct order.invoiceItemCollection.comparator = function(model) { return model.get("price"); };
The
comparator
callback accepts a single parameter, which is a model object. It should return a value according to which the collection is sorted.Optionally, call the
sort()
method to force sorting.invoiceItemCollection.sort();
Check the result.
invoiceItemCollection.pluck("price"); // [8, 15, 17, 22]
When the comparator
callback is defined, Backbone uses it to insert a new model in the models
array so that it is inserted in the correct order.
If you assign a new comparator
callback to a collection with existing models, you need to trigger sorting manually by calling the
sort()
method.
You also need to call the sort...