Monday, November 18, 2024
Google search engine
HomeLanguagesJavascriptBackbone.js sort Collection

Backbone.js sort Collection

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

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

RELATED ARTICLES

Most Popular

Recent Comments