Backbone.js Collections (original) (raw)

Last Updated : 25 Jul, 2022

A Backbone.js Collections are a group of related models. It is useful when the model is loading to the server or saving to the server. Collections also provide a helper function for performing computation against a list of models. Aside from their own events collections also proxy through all of the events that occur to the model within them, allowing you to listen in one place for any change that might happen to any model in the collection.

Now we will see the working of collections.

Syntax: We can create a collection with extending syntax as follows

let collection = Backbone.Collection.extend ( Properties , [ ClassProperties ] );

Properties:

Example 1: In this example, we will create a collection and pass the argument as a list of models creating the array. The following code shows how we can add a list of models at the creation of the Collection.

HTML `

Backbone.js Collections
<script src=

"https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.3.3/underscore-min.js" type="text/javascript">

<script src=

"https://cdnjs.cloudflare.com/ajax/libs/backbone.js/1.1.0/backbone-min.js" type="text/javascript">

<!-- Javascript code -->
<script type="text/javascript">
    var car = Backbone.Model.extend();
    var collection = Backbone.Collection.extend({
        model: car,
    });

    var Coll_car = new collection();

    Coll_car.add(new car({ Brand: "BMW", color: "blue" }))
    Coll_car.add(new car({ Brand: "Audi", color: " red" }))
    Coll_car.add(new car({ Brand: "Verna", color: "black" }))
    Coll_car.add(new car({ Brand: "Tata nano", color: "green" }))

    console.log(Coll_car);
</script>
z

`