Backbone.js extend Collection

In this article, we will see the Backbone.js extend collection. The Backbone.js extend collection can be used to extend the backbone’s collection class in which we can create our own collection. It also facilitates the instance properties & the optional classProperties that are attached to the constructor function of the collection directly.

Syntax:

Backbone.Collection.extend(properties, classProperties)     

Parameters: It will take 2 parameters, which are described below:

  • properties: This parameter provides the instance properties for the specified collection class.
  • classProperties: This class property is attached to the collection’s constructor function.

Example 1: In this example, we will extend a collection by creating one value.

HTML




<!DOCTYPE html>
<html>
  
<head>
    <title>
      Backbone.js extend Collection
    </title>
    <script src=
"https://code.jquery.com/jquery-2.1.3.min.js" 
            type="text/javascript">
    </script>
    <script src=
"https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.2/underscore-min.js" 
            type="text/javascript">
    </script>
    <script src=
"https://cdnjs.cloudflare.com/ajax/libs/backbone.js/1.1.2/backbone-min.js" 
            type="text/javascript">
    </script>
</head>
  
<body>
    <script>
        var data = Backbone.Model.extend({
            defaults: {
                id: '1',
                name: 'w3wiki User',
            },
        });
        var data1 = Backbone.Collection.extend({
            model: data,
        });
        var final = new data1({});
        document.write('Values : ', JSON.stringify(final));
    </script>
</body>
</html>


Output:

Values : [{"id":"1","name":"w3wiki User"}]

Example 2:  In this example, we will extend a collection by creating multiple values.

HTML




<!DOCTYPE html>
<html>
  
<head>
    <title>
       Backbone.js extend Collection
    </title>
    <script src=
"https://code.jquery.com/jquery-2.1.3.min.js" 
            type="text/javascript">
    </script>
    <script src=
"https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.2/underscore-min.js" 
            type="text/javascript">
    </script>
    <script src=
"https://cdnjs.cloudflare.com/ajax/libs/backbone.js/1.1.2/backbone-min.js" 
            type="text/javascript">
    </script>
</head>
  
<body>
    <script type="text/javascript">
        var data = Backbone.Model.extend({
            defaults: {
                id: '1',
                name: 'w3wiki User',
                address: 'New Delhi',
            },
        });
        var data1 = Backbone.Collection.extend({
            model: data,
        });
        var final = new data1({});
        document.write('Values : ', JSON.stringify(final));
    </script>
</body>
</html>


Output:

Values : [{"id":"1","name":"w3wiki User","address":"New Delhi"}]

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



Contact Us