Open In App

What is Collection in Backbone.js ?

Collections in backbone.js are ordered sets of model. We can define the type of the model and the instance of properties for a collection. we can also bind “change” events to be notified whenever a model present in the collection is modified, we can also listen for “add” and “remove” events, and also fetch the collection from the server. The creation of the collection is to serve the event binding whenever any modification is made in the collection. The data is retrieved from the database and is populated using models and collections with the help of custom binding events.

Syntax: (by extending the class)



Backbone.Collection.extend( properties, classProperties )   

Parameter description:

There are various methods associated with backbone collection: 



Backbone collection methods are as follows:

Example 1: In this example, we will be using the button to show the data.




<!DOCTYPE html>
<html>
  
<head>
    <title>collection example</title>
            type="text/javascript">
    </script>
    <script src=
            type="text/javascript">
    </script>
    <script src=
           type="text/javascript">
    </script>
</head>
  
<body style="background-color:black;">
    <h1 style="color:green;">GeeksforGeeks</h1>
    <button onclick="invoke()">Show data:</button>
  
    <script type="text/javascript">
        var data_collection = Backbone.Model.extend({
            defaults: {
                website: "GeeksForGeeks",
                rating: 10
            },
        });
        var example = Backbone.Collection.extend({
            model: data_collection
        });
        function invoke() {
            var Z = new example({});
  
            document.write("Collection: ", JSON.stringify(Z));
        }
    </script>
</body>
  
</html>

Output:

 

Example 2: In this example, we will direct the collection of data.




<!DOCTYPE html>
<html>
  
<head>
    <title>collection example</title>
            type="text/javascript">
    </script>
    <script src=
            type="text/javascript">
    </script>
    <script src=
            type="text/javascript">
    </script>
</head>
  
<body>
    <script type="text/javascript">
        var data_collection = Backbone.Model.extend({
            defaults: {
                website: "GeeksForGeeks",
                rating: 10
            },
        });
        var example = Backbone.Collection.extend({
            model: data_collection
        });
        var Z = new example({});
        document.write("Collection: ", JSON.stringify(Z));  
    </script>
</body>
  
</html>

Output:

 

Reference: https://backbonejs.org/#Collection


Article Tags :