Home » Backbone » Backbone collections

Backbone collections

Welcome to the Third module of Backbone.js tutorial. In this Module we will cover some basic concepts of backbone collections, how collections can be created and instantiated, how we can add and delete models to a collection, how to get the value from collections and how can we set the value dynamically. Moving further we will see how can we sort the collection data and at last collection events.

These are the topics that we will be covering in this module

  • Defining and Initializing
  • Add and remove models
  • at
  • get
  • set
  • reset
  • sorting
  • collection events

 

Collections

Collection is a set of related models like for example you can have a collection of car models. If you want to apply some logic on set of models then you can directly write that logic in collection which will be applied on all the models. Collections can be used to sort the models and can also be used to apply some filtering logic on models. In upcoming topics you will learn more about all these concepts of collections, So let’s start by defining and initializing our first collection.

 

Defining and Initializing

Same as model and view, Collection can be defined by using Backbone.Collection.extend()

Like models, you can define class properties directly on collections rather than on collection’s instance by passing them as second parameter of extend method.

Let’s create a simple collection snippet

// creating concrete model
var carModel = Backbone.Model.extend({});

//1st model of carModel type
var BentleyModel = new carModel();
                BentleyModel.set({type:"Bentley", carModel:"Bentley Flying Spur", price:'11', rank:3});

//2nd model of carModel type
var BugattiModel = new carModel();
                BugattiModel.set({type:"Bugatti", carModel:"Bugatti Veyron", price:'14', rank:4});

//3rd model of carModel type
var BMWModel = new carModel();
                BMWModel.set({type:"BMW", carModel:"BMW X3", price:'12', rank:2, id:2})

//4th model of carModel type
var FerrariModel = new carModel();
                FerrariModel.set({type:"Ferrari", carModel:"Ferrari 458 Italia", price:'15', rank:5});

// car collection
var carCollection = Backbone.Collection.extend({
                model:carModel, // model name
});

//passing array of carModels on collection instantiation
var mCarCollection = new carCollection([BentleyModel, BugattiModel, BMWModel, FerrariModel]);

console.log(mCarCollection.length);
// console: 4

Above example has four models of same type which have been passed to collection.

Let’s try to put “carCollection” in HTML.

HTML

<table border="1">
   <tr>
      <td>TYPE</td>
      <td>MODEL</td>
      <td>PRICE</td>
      <td>RANK</td>
   </tr>

<script type="text/html" id="id_collectionData">
   <tr>
       <td><%=model.type%></td>
       <td><%=model.carModel%></td>
       <td><%=model.price%></td>
       <td><%=model.rank%></td>
    </tr>
</script>
</table>

Collection.js

var mainView = Backbone.View.extend({
                  initialize:function(){
                  this.model = mCarCollection.models;
                  },
                  model:null,
                  render:function(){
                     var self= this;
                     var carTemplate = $('#id_collectionData').html();
                     _.each(this.model,function(model){
                         self.$el.append(_.template(carTemplate,{model:model.attributes}));
                     });
                     return this;
                 }
            });

var view = new mainView({el:'body'});
view.render();

Above code is pretty much self-explanatory, which will result in below table.

backbone_collection_table

 

Add and remove models

In above example we defined few models and passed them as an object array to collection. Another way of adding the model to collection is by using add() method.

add() method is used to add the model to the collection, likewise remove() method is used to remove model from the collection.

add() method allows to add multiple models at once by separating them with comma(,). If you pass {merge: true} then the values will be updated with new values. Let’s take a look:

I am using the collection “mCarCollection” to perform add() and remove().

// Adding model
mCarCollection.add([{type:"Maybach", carModel:"Maybach 62", price:'35', rank:9}]);

// Adding multiple models at once
var PorscheModel = new carModel();
       PorscheModel.set({type:"Porsche", carModel:"Porsche Carrera GT", price:'48', rank:6});

mCarCollection.add([{type:"Pagani", carModel:"Pagani Zonda C12 ", price:'17', rank:1},{type:"Koenigsegg", carModel:"Koenigsegg CCX", price:'6', rank:7},PorscheModel]);

// Replacing values using {merge:true}

//To demonstrate this lets add one more attribute to BMWModel id:3

var BMWModel = new carModel();
       BMWModel.set({type:"BMW", carModel:"BMW X3", price:'12', rank:2, id:3});

// now create one more model with same id and add it to collection.

mCarCollection.add([{type:"Mercedes", carModel:"Mercedes SLR McLaren", price:'45', rank:5, id:3}],{merge: true});

In this case BMWModel’s values will be replaced by this newly added model because id of both the models is same and I am passing {merge:true}.

  • Remove model:

To remove the model you just need to call remove() method on collection and pass the model name you want to remove.

mCarCollection.remove(BentleyModel);

This will remove “BentleyModel” from mCarCollection.

 

at

Sometime you have a requirement that you need to insert new model at some particular position in collection array, in that case you can use backbone collection’s at property. at property allows you to insert the model at specific index by passing the index value. Let’s check out the below example

var LamborghiniModel = new carModel();
       LamborghiniModel.set({type:"Lamborghini", carModel:"Lamborghini Gallardo", price:'19', rank:1});

mCarCollection.add(LamborghiniModel, {at:2});

Above code will add “LamborghiniModel” at index value 2, i.e. 3rd position as index starts from 0.

 

get

In Backbone you can fetch a model from collection. You can do that by using get() method.

In get() method you can pass model’d id.

var fetchedModel = mCarCollection.get(2);
console.log(fetchedModel);
// console: will return BMWModel data

 

set

Instead of performing add() and remove() separately on collection, backbone provides the mechanism to do all this at once by using set() method.

Set() function is the easiest way to add and remove models from collection in single step. Other than that set() function fires add, remove and change events also which can be used to render the UI with updated values.

// creating model
var carModel = Backbone.Model.extend({});

//1st model of carModel type
var BentleyModel = new carModel();
      BentleyModel.set({type:"Bentley", carModel:"Bentley Flying Spur", price:'11', rank:3});

//2nd model of carModel type
var BugattiModel = new carModel();
      BugattiModel.set({type:"Bugatti", carModel:"Bugatti Veyron", price:'14', rank:4});

//3rd model of carModel type
var BMWModel = new carModel();
      BMWModel.set({type:"BMW", carModel:"BMW X3", price:'12', rank:2, id:2});

//4th model of carModel type
var FerrariModel = new carModel();
      FerrariModel.set({type:"Ferrari", carModel:"Ferrari 458 Italia", price:'15', rank:5});

//5th model of carModel type
var PorscheModel = new carModel();
      PorscheModel.set({type:"Porsche", carModel:"Porsche Carrera GT", price:'48', rank:6});

// creating car collection
var carCollection = Backbone.Collection.extend({
           model:carModel
});

var mCarCollection = new carCollection([BentleyModel, BugattiModel, BMWModel, FerrariModel]);

// Binding "add" event on mCarCollection
mCarCollection.on('add',function(model){
                console.log("added  "+model.get('carModel'));
});

// Binding "remove" event on mCarCollection
mCarCollection.on('remove',function(model){
                console.log("removed  "+model.get('carModel'));
});

// Binding "change" event on mCarCollection
mCarCollection.on('change',function(model){
                console.log("changed  "+model.get('carModel'));
});

FerrariModel.set({price:'21', rank:1});

mCarCollection.set([BentleyModel,BugattiModel,FerrariModel,PorscheModel]);

// console:
// changed Ferrari 458 Italia
// removed BMW X3
// added Porsche Carrera GT

 

reset

remove() method is used to remove particular value from collection, but what is you want to delete all the values from collection? Or what if you want to replace all the existing values with new values? In that case you can use reset() function which resets previous values with new values. For example, if you want to remove everything from collection and pass new values, then reset() function is what you need. reset() function fires “reset” event on collection.

By using “options.previousModels” you can also determine the previous data i.e. the data before reset executed on collection.

var PorscheModel = new carModel();
        PorscheModel.set({type:"Porsche", carModel:"Porsche Carrera GT", price:'48', rank:6});

var LamborghiniModel = new carModel();
       LamborghiniModel.set({type:"Lamborghini", carModel:"Lamborghini Gallardo", price:'19', rank:1});

// new array
var mCarCollection = new carCollection([BentleyModel, BugattiModel, BMWModel, FerrariModel]);
console.log(mCarCollection);

// console: child {length: 4, models: Array[4], _byId: Object, constructor: function, model: function…}

// resetting mCarCollection and passing new set of array.
mCarCollection.reset([PorscheModel,LamborghiniModel]);
console.log(mCarCollection);

// console: child {length: 2, models: Array[2], _byId: Object, constructor: function, model: function…}

In above example the mCarCollection will have new array. i.e. PorscheModel and LamborghiniModel

If you completely want to remove everything from collection than you can directly call reset() function on collection without passing any parameter.

mCarCollection.reset();
console.log(mCarCollection);

// console: child {length: 0, models: Array[0], _byId: Object, constructor: function, model: function…}

Binding reset event with collection.

//this collection has 4 models
var mCarCollection = new carCollection([BentleyModel, BugattiModel, BMWModel, FerrariModel]);
console.log(mCarCollection);

//console: child {length: 4, models: Array[4], _byId: Object, constructor: function, model: function…}

// attaching reset event
mCarCollection.on('reset',function(model,options){

//options.previousModels will return the array of previous models
                console.log(options.previousModels);

//console: This will return array of four models: BentleyModel, BugattiModel, BMWModel, FerrariModel
});

mCarCollection.reset([PorscheModel,LamborghiniModel]);
console.log(mCarCollection);

// console: child {length: 2, models: Array[2], _byId: Object, _events: Object, constructor: function…}

Above code will reset the mCarCollection with new set of values and will display previous values in console.

 

sorting

Backbone collection can sort the model according to user’s requirement. User can pass the sort condition to comparator() function.

var carCollection = Backbone.Collection.extend({
                model:carModel,
                comparator:function(car){
                   return car.get('rank');   
                }
            });

var mCarCollection = new carCollection([BentleyModel, BugattiModel, LamborghiniModel,BMWModel, FerrariModel]);

Above code will sort the data according to model’s “rank” attribute. You can pass any model attribute to comparator. To disable sorting when adding a model, pass {sort: false} to add() method.

 

collection events

We have reached to the end of this module, we have already covered almost all the collection events in above examples like add, remove and change. Please go through each of the event and if you still have any doubt please leave a comment and i will revert back to you ASAP.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>