Working with Backbone.Collection : Part 6

If you are new to this series of Backbone.js, I recommend you go through the previous articles:

Backbone.Collections

Collections hold instances of models, in other words an ordered set of models that provide various types of methods for various operations. In this tutorial we will discuss these methods.

Creating a Collection

extend
Backbone.Collection.extend(properties, [classProperties])

This is similar to what we did with the Backbone.Model and Backbone.View classes. We created a Model and View by simply extending the respective classes of Backbone. A Collection can also be created by simply extending a Collection class of Backbone. By extending the Collection class, it also makes the collection constructor function to be attached with properties like instance properties and optional classProperties that hold the model.
  1. var Company = Backbone.Collection.extend({   
  2. // Collection created// specification of Model here  
  3. });  
As we learned, a Collection is an ordered set of Models which means it holds and specifies the models. Let's create a model that will be later held by a collection. Here I will use the previous article's model.

The following is an example:
  1. var Employee = Backbone.Model.extend({ // creating a model  
  2. defaults: {  
  3. Fname: 'ishriss',  
  4. DeptNo: 24,  
  5. position:'Developer'  
  6. },  
  7. });  

 The preceding model is held by the Company Collection. It is done by the model attribute of the Collection class as follows.

  1. var Company = Backbone.Collection.extend({ // creating a Collection,will hold Model  
  2. model:Employee // model property will specify Employee Model.  
  3. });  
Instantiation of Collection

constructor / initialize

new Backbone.Collection([models], [options]) 

As we discussed about the instantiation of other classes like Model and Views in previous articles/tutorials, similarly a Collection class is also instantiated using the "new" keyword. Invocation of the initialize function is done when we create the collection. When creating a collection we can a model array.

  1. var IBM = new Company(); //instantiating without ing object  
ing an array of objects:
  1. var developer = new Employee({ name: "iShriss", DeptId: 01 });  
  2. var designer = new Employee({ name: "Steve", DeptId: 02 });  
  3. var csharp = new Company([developer, designer]);// ing an array objects  

 toJSON
collection.toJSON([options])

Likewise in Model, it returns a copy of model attributes in a collection. It is used to serialize the collection. In Model in Backbone.JS : Part 2 we already discussed toJSON where it returns a copy of the current attributes.

  1. var Employee = Backbone.Model.extend({ // creating a model  
  2. defaults: {  
  3. Fname: 'ishriss',  
  4. DeptNo: 24,  
  5. position: 'Developer'  
  6. },  
  7. });  
  8.   
  9. var Company = Backbone.Collection.extend({ // creating a Collection,will hold Model  
  10. model: Employee // model property will specify Employee Model.  
  11. });  
  12. var developer = new Backbone.Collection([  
  13. {name: "iShriss", Dept: 01},  
  14. {name: "Adam", Dept: 02},  
  15. {name: "Steve", Dept: 03}  
  16. ]);  
  17. console.log(JSON.stringify(developer));  
Chrome Console Output


Adding Models 

add
collection.add(models, [options])

The Backbone.Collection class offers an add method to add a model or an array of models to the collection as well as raw attribute objects. Ensure that the model you want to add is not already in the Collection; if it is already there then the model will be ignored. This method returns added models.

 

  1. var tester = new Employee({ name: "Rizwan", DeptId: 03 });  
  2. csharp.add(tester); //tester model add  

Backbone.Collection also allows us to add multiple models, this can be done by ing a model array in the add method as follows.

  1. var leader = new Employee({ name: "Bill", DeptId: 4 });  
  2. var manager = new Employee({ name: "Adam", DeptId: 5 });  
  3. csharp.add([leader, manager]); //adding multiple models  

Removing Models

remove
collection.remove(models, [options])

A Backnone.Collection class also offers a remove method to remove models or an array of models from a collection. The Model is removed from the collection on the base of the index available in the collection. It will remove a specific model at a time.

  1. var ceo = new Employee({ name: "Tim", DeptId: 6 });  
  2. csharp.add(ceo);  
  3. csharp.remove(ceo); // will remove ceo model  

On the other hand, if we wanted to empty the existing Collection, Backbone offers the reset method for this purpose. All we need to do is to call collection.reset.

Method without ing any arguments.

It is further used to replace a collection with a new models list that will return the recently set models.

  1. csharp.reset(); // empty the collection  
  2. csharp.reset([,]); // reset and add model array.  

Size of Collection[No of models]

length
collection.length

As we know a Collection contains a models.Backbone.Collection that provides a property called length that counts the number of models held by collection.Length.

Property acts just like when we calculate the size of an array.

  1. var apple = new Company([developer, designer]);  
  2. console.log(apple.length); // will return no. of models in apple collection i.e, 2  
Let's look at the Chrome Console.



SMART Setting

set 
collection.set(models, [options])
 

The Set method is responsible for the update of a collection with a set of models. It looks at the model, whether or not it is already in the collection. If it isn't then it will be added to the collection. The merging of attributes is done only if that model is already in the collection. 

  1. var Employee = Backbone.Model.extend({ // creating a model  
  2. defaults: {  
  3. Fname: 'ishriss',  
  4. DeptNo: 24,  
  5. position:'Developer'  
  6. },  
  7.   
  8. });  
  9. var Company = Backbone.Collection.extend({ // creating a Collection,will hold Model  
  10. model:Employee // model property will specify Employee Model.  
  11. });  
  12. var developer = new Employee({ name: "iShriss", DeptId: 01 });  
  13. var designer = new Employee({ name: "Steve", DeptId: 02 });  
  14. var leader = new Employee({ name: "Bill", DeptId: 4 });  
  15. var ceo = new Employee({ name: "Tim", DeptId: 6 });  
  16. var apple = new Company();  
  17. apple.add(developer);  
  18. apple.add(designer);  
  19. apple.add(leader);  
  20. apple.set([developer, { name: "shris", DeptId: 02 }, ceo]);  
  21. // set method will remove leader model,will add ceo model, changed designer model  

get
collection.get(id

Collection.get gets a model from the collection. We need to the id.

  1. var model = collection.get(id); // using get method  
  2. var developer = csharp.get(101); //example  

The following are some other important methods/attributes:



Summary

Backbone.Collection holds model instances, we can define a Collection by extending the Backbone.Collection.Model attribute to specify the model instance. Explaining the entire collection is beyond the scope of this article, for more information you can look at the Backbone.js documentation at http://backbonejs.org/#Collection. Stay in touch with the loop of this article series, there are many more features of Backbone.js is to be discussed in future articles.

Cheers! 

Up Next
    Ebook Download
    View all
    Learn
    View all