Introducing BACKBONE COLLECTION

A Collection in Backbone.js is a set of similar type of models. It is helpful while working with a set of models.

Events triggered on a model in a collection are also triggered on the collection, thus making it easier to perform any operation while working with collection.


Small Example

We will build a small ‘My Contacts’ application to understand Backbone Collection. Shown below is the application that we will be building:

My Contacts


Add Contact
Contact Name :
Contact Number :
Email Id :
Add Contact

Contact List


The Model

Shown below is our model which has 3 attributes, name, email and mobile.

var Contact = Backbone.Model.extend({
		
    defaults : {
	name:"",
	email:"",
	mobile:""
    }
});

The Collection

Below is our Backbone Collection, to create a Backbone collection we need to extend the Backbone.Collection. We have specified the 'model' property and the 'modelId' method in our collection.

The 'model' property is used to specify the model the collection will work on. In our case its the Contact model we created earlier.

The 'modelId' method should return the attribute of the model, which will be used to uniquely identify a model in a collection. By default, it returns the 'idAttribute' of the model, or if idAttribute is not found it returns the 'id'. In our case we want the 'name' to be used to uniquely identify our models in the collection, so we have overridden the modelId method to return the name attribute.

var ContactList = Backbone.Collection.extend({
		
    model : Contact,

    modelId : function(attrs){
	return	attrs.name;
    }
});

The Views

We are using 2 views for our application, 'ContactView' which is our top-level view, and the 'ContactItemView' which is the view used for each contact we add. 

The 'ContactView' is shown below. Here we have specified the DOM element for this view as the top level div (with id contactListApp) using the el property.

We have bound the click event on the add button to the addNewContact method. The view also listens to any addition/removal (add/remove events) of models in the collection and renders the count accordingly.

The addNewContact method uses the get method of the collection to check for the existence of the contact with same name. The same attribute is used in the get method that is returned by the modelId method. If the contact is not present in the collection we create a new contact model and its view after which we add it into the collection using the add method.

The collection maintains a length property, which contains the number of models in the collection at any point of time. We are using this property to update the count of contacts.

var ContactView = Backbone.View.extend({
		
    el: $("#contactListApp"),

    events : {
	"click #add" : "addNewContact"
    },

    initialize: function(){
	this.listenTo(contactList, 'add', this.updateCount);
	this.listenTo(contactList, 'remove', this.updateCount);
    },

    addNewContact: function(){
	if(contactList.get($("input[name='name']").val()) != undefined){
	    alert("Contact Already Exists !");
	    return;
	}

	var newContact = new Contact({
	    'name' : $("input[name='name']").val(),
	    'mobile' : $("input[name='mobile']").val(),
	    'email' : $("input[name='email']").val()
	});
	var contact = new ContactItemView({model:newContact});
	$("#contact-list").append(contact.render().el);
	    contactList.add(newContact);
	},

    updateCount: function(){
	    $("#count").html("Total :"+ contactList.length + " Contacts");
    }

});

Below is the ContactItemView. This view gets created/destroyed as and when contacts (model) are added/removed to the collection.

Notice the remove method in deleteContact, which is used to remove a model from the collection.

var ContactItemView = Backbone.View.extend({

    template: _.template($("#contactList").html()),
		
    events: {
	"click .button.delete" : "deleteContact"
    },

    render: function(){
	this.$el.html(this.template(this.model.toJSON()));
	return this;
    },

    deleteContact : function(){
	contactList.remove(this.model);
	this.model.destroy();
	this.remove();
    }

});

The HTML Page

The html source code is shown below. Notice the collection.js imported in this page. This is where our model, views and collection reside. Click here to view the js file.

<!DOCTYPE HTML>
<html>
<head>
    <title>Backbone Collection</title>
    <script type="text/javascript" src="js/json2.js"></script>
    <script type="text/javascript" src="js/jquery.min.js"></script>
    <script type="text/javascript" src="js/underscore.js"></script>
    <script type="text/javascript" src="js/backbone.js"></script>
    <script type="text/javascript" src="js/collection.js"></script>
</head>
<body>
    <div id="contactListApp">
        <h2>My Contacts</h2>
        <div class="contact-input">
            <fieldset>
            <legend style="font-size:20px">Add Contact</legend>
            <table>
                <tr>
                    <td>Contact Name :</td>
                    <td><input name="name" type="text"></td>
                </tr>
                <tr>
                    <td>Contact Number :</td>
                    <td><input name="mobile" type="text"></td>
                </tr>
                <tr>
                    <td>Email Id :</td>
                    <td><input name="email" type="text"></td>
                </tr>
                <tr>
                    <td><a href="#" class="button" id="add">Add Contact</a></td>
                    <td></td>
                </tr>
            </table>
            </fieldset>
        </div>
        <div class="contacts">
            <h3>Contact List</h3>
            <div id="contact-list"></div>
            <div id="count"></div>
        </div>
    </div>

    <script type="text/template" id="contactList">
        <div class="contact">
            <h3><%- name %></h3>
            <span><%- mobile %></span>
            <span><%- email %></span><br>
            <a href="#" class="button delete">Delete Contact</a>
        </div>
        <hr>
    </script>
</body>
</html>
RELATED ARTICLES

A Glance at Backbone.js

Backbone.js is a JavaScript framework that attempts to structure a web application by separating the domain data & business logic from the user interface.

View Article

Understanding Model and View in Backbone.js

Model and View are special objects that form an integral part of Backbone.js. These are used to keep the data and the business logic separate from the user interface.

View Article