× Please, log in to give us a feedback. Click here to login

You must be logged to download. Click here to login


MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation


MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

Backbone.js Collection

In this article we will continue talking about Backbone.js. Now we will talk about Collections.

We have covered backbone model in the previous article “Backbone.js: Getting Deeper into Model”. A model is a representation of data which has its own property or set of functions inside. It is represents a single data although it may contains multiple properties and functions. Remember the scenario we use in the previous article, we are creating an image gallery app, so if you haven’t read it, I recommend you to read it first and then back here. In our gallery image app, the model represents single image. But a gallery should have many images, right? Yes our gallery app contains a collection of images. In this case we use Backbone collection to gather each model of image.

So let’s make us clearer, each backbone model represents each single image we have in our gallery. A backbone collection represents a collection of images which is I can say it is the gallery itself.

Illustration of Model and Collection

Figure 1: Illustration of Model and Collection

We can create a model by extending from ‘Backbone.Model’, as simple as that we can create a collection. We need to extend from ‘Backbone.Collection’. See the listing below.

Listing 1 : Create Backbone Collection

//first create a model
	var imageModel = Backbone.Model.extend({
		defaults: {
			title : ‘untitled’,
			description : ‘no description available’,
			owner: ‘Muhammad Azamuddin’,
			date: ’29 March 2013’

//create  backbone collection
var galleryCollection = Backbone.Collection.extend({
	model : imageModel // tell the collection which Model to collect inside it.
//create a new gallery
var imageGallery = new galleryCollection();

Let me explain the listing above, before creating a collection first we create backbone model. This is important because later we will tell the collection which model to use/collect. So we create model named ‘imageModel’ which will be used to store information about each image in our app. Remember in the previous article we created a single image manually after defining a model, we do it like this.

Listing 2: Create new image based on the ‘imageModel’

	var firstImage = new imageModel(); 

But now, since we are working with collection we don’t need to do that. We will let the collection do it for us, we can later add a new image directly from the collection.

Back to explanation of listing 1, we create a collection named ‘Gallery’ by extending from ‘Backbone.Collection’. And then we tell the collection to use imageModel, we do it like this ‘model : imageModel’, after that, finally we create image gallery. Okay, so what happened now that the collection using imageModel? It’s pretty much like this:

  1. The ‘Gallery’ collection is a collection of model named ‘imageModel’,
  2. We can add, change, or remove model and its property directly from this collection,
  3. If we add new data to collection, the collection will create new ‘imageModel’ and store the data inside it,
  4. We can manipulate the organisation of model inside it, like filtering, sorting, etc.

Adding data to collection

This is the fun part of this tutorial, like I said we can now adding new data image to our gallery app directly from collection instead of manually adding to model. What you should always keep in mind is collection in any case related to model. let’s see listing below.

Listing 3: Adding image to collection

//we are continuing from listing 1. 
imageGallery.add({}); //add new image with no properties supplied

This line of code will create a new image based on the ‘imageModel’ (because in the listing 1 we told the collection to use ‘imageModel’) then store it to the collection imageGallery, so now the imageGallery collection has one model inside it. Because we do not supply any property upon adding, the newly created image will use the defaults properties defined in the ‘imageModel’ (see listing 1).

Listing 4: Adding new image with properties

imageGallery.add({ title : ‘awesome pic’, description : ‘I love this pic’, owner : ‘Azam’, date : ’29 March 2013’ }); 

I think this one is pretty clear, it will add new image with the properties supplied and store it to ‘imageGallery’ collection. The properties are stored as JSON.

Listing 5: Adding multiple images to collection

//create array of image and its properties
var images  = [
	{ title : ‘image 3’, description : ‘so natural, owner : ‘Azam’, date : ’29 March 2013’ },
	{ title : ‘image 4’, description : ‘beautiful one’, owner : ‘Claire’, date : ’30 March 2013’ },
{ title : ‘image 5’, description : ‘amazing scene’, owner : ‘John’, date : ’3 April 2013’ }
//create new collection

To add multiple images, first we store list of images in an array called ‘images’ which contains multiple image objects.The properties supplied in the object should match the default properties defined in the model ‘imageModel’ (see listing 1), otherwise it will create new property and will also have defaults property. And then we simply pass that array to add method.

Getting a Model from collection

There are some ways to get a model from collection, the first method is using Collection.get() which accept single index of model as parameter like follows.

Listing 6: Get model from collection


Another way to retrieve model from collection is by client id or CID as follows

Listing 7: Get model from collection by client id


Underscore utility functions

In the article “Introduction to Backbone.js” I mention that backbone depends on utility belt called underscore thus backbone can use some power of underscore to ease our development process. In this section we’re gonna use some of them.


Listing 8: Filter a collection

var filterByOwner = _.filter(imageGallery.models, function(image){
	return image.get(‘owner’).toLowerCase() === ‘azam’;

In the listing above ‘filterByOwner’ will return list of model from imageGallery collection that has owner property equal to ‘azam’. We can later reset the collection and pass this filtered list.


Listing 9: Sort a collection

var sortByTitle = imageGallery.sortBy(function(image){
	return image.get(‘title’).toLowerCase();

The sortByTitle will return a list of images from ‘imageGallery’ collection that has been sorted by image title.

Fetching models from server

To retrieve models from our server we use Collections.fetch(), it retrieves a default set of models from the server in the form of JSON array. When this data arrives, the current collection’s content will be replaced with the contents of the array.

var imageGallery = new Backbone.Collection;
imageGallery.url = '/images';

Under the covers, Backbone.sync is the function called every time Backbone tries to read or save models to the server. It uses jQuery or Zepto’s ajax implementations to make these RESTful requests, however this can be overridden as per your needs.

Resetting models in a collection

Sometimes we might want to change the whole list of models inside collection, for example if we want to filter the collection in a certain condition. To do this we use Collection.reset(), it will reset the entire collection with new list of models we supply. See the listing below.

Listing 10: Reset Collection with new models

//we are going to filter collection 
//first we need to retrieve the filtered models from the existing collection like in the listing 8
var filterByOwner = _.filter(imageGallery.models, function(image){
	return image.get(‘owner’).toLowerCase() === ‘azam’;
//now reset the existing ‘imageGallery’ collection with filtered models list

Let me explain what’s going on here, first we use underscore utility function (_.filter) to get new list of models that has been filtered. This new list of model is assigned to ‘filterByOwner’. Then we call the Collection.reset() and pass filterByOwner. Thus the collection now will be updated and contains new list of filtered models.

What just you see will actually trigger a reset event, another important part of Backbone is the events. It provides control over how your application can react to user interaction. Models, Collection, and Views has events such as ‘add’, ‘destroy’, ‘reset’, ’change’ etc. Then the corresponding part will be able to listen to an event triggered inside it or from outside. We will cover backbone events in the next tutorial.

Okay, it’s enough for now, I hope you enjoy the tutorial and if you have any question or suggestion don’t hesitate to leave a comment below. See you next time!

A passionate and visionary web developer who falls in love with web technologies. Always excited to learn more, just like you.

What did you think of this post?
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!

> More info about MrBool Credits
You must be logged to download.

Click here to login