In this article, we will see the sort collection in Backbone.js along with understanding the basic implementation through the example. The Backbone.js sort collection is used to sort the elements in the given collection (input collection), i.e. forcing the items to be re-sort themselves. Whenever the model is included, the collection will sort the item itself automatically with the comparator. In order to disable the sorting while model is included, pass the sort with the value as false to the add collection. By calling the sort will trigger the sort event on the collection.
Syntax:
collection.sort([options]);
Parameter Value: It will take only one parameter:
- options: This parameter has 2 possible values i.e. “true” or “false”. If it is true, then sorting will be enabled. If it is false, then it is disabled.
Example: In this example, we will create a collection with 5 items and sort them using the sort Collection in Backbone.js.
HTML
<!DOCTYPE html> < html > < head > < script src = type = "text/javascript" > </ script > < script src = type = "text/javascript" > </ script > < script src = type = "text/javascript" > </ script > </ head > < body > < script type = "text/javascript" > var Food = Backbone.Model.extend(); var Foods = [{ food: 'chicken', cost: '172' }, { food: 'peas', cost: '382' }, { food: 'icecream', cost: '312' }, { food: 'milk', cost: '932' }, { food: 'eggs', cost: '18' }]; var final = new Backbone.Collection(Foods, { model: Food, comparator: 'food' }); document.write("Items after Sorting: ", JSON.stringify(final.toJSON())); </ script > </ body > </ html > |
Output:
Items after Sorting: [{"food":"chicken","cost":"172"}, {"food":"eggs","cost":"18"}, {"food":"icecream","cost":"312"}, {"food":"milk","cost":"932"}, {"food":"peas","cost":"382"}]
Reference: https://backbonejs.org/#Collection-sort