Model in Backbone.JS : Part 2

Model in Backbone.JS 

In this article I am trying to put some light on model on Backbone, after providing an overview of Backbone modules collectively.

If you have not gone through my previous article then I recommend you to go through my previous article.

In this session, I will only concentrate on Backbone.

Setting Up Working Environment

In this tutorial we will add 3 JavaScript library files to set up our working environment, namely Underscore.js, jQuery and Backbone.js files. These libraries are loaded by the HTML file. 

  1. <!DOCTYPE html>  
  2. <html xmlns="http://www.w3.org/1999/xhtml">  
  3. <head>  
  4. <title></title>  
  5. <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script>  
  6. <script type="text/javascript" src="http://ajax.cdnjs.com/ajax/libs/underscore.js/1.1.4/underscore-min.js"></script>  
  7. <script type="text/javascript" src="http://ajax.cdnjs.com/ajax/libs/backbone.js/0.3.3/backbone-min.js"></script>  
  8. </head>  
  9. <body>  
  10. <script type="text/javascript">  
  11.   
  12. </script>  
  13.   
  14. </body>  
  15. </html>  

In this article I will be using the Google Chrome browser and the Chrome console to try various things related to models in Backbone.js.

When you open the preceding file in the Chrome browser, open the Chrome console to dispaly the data. To get the Chrome console screen you need to open that HTML file in Google Chrome.

Go to Google Chrome > More Tools > Developer Tools > Console or

Go to Google Chrome > More Tools > JavaScript Console or simply by pressing F12.

Now let's move on to the Model.

Model

If you had gone through my previous article then you probably understand the basics of models, that is what a model in Backbone actually is.

Models are core modules of Backbone.js containing interactive data, retreves data and contains the surrounding code such as data validation, default values, data initialization, conversions and so on.

A Model is created by simply extending Backbone.Model as follows: 

  1. Student = Backbone.Model.extend({  
  2.   
  3. });  

Instantiating Model

A Model is instantiated using the "new" keyword as: 

  1. var model = new Backbone.Model.extend();  

 You can also do it using a custom type. Here is how it is: 

  1. Student = Backbone.Model.extend({  
  2.   
  3. });  
  4.   
  5. var Shriss = new Student();  

 Initialize in Model

After the instantiation of the model is done the work of initializing the function is to be done just like constructors in a class.

Initialize is defined as new Model([attributes], [options]). The initialize function is invoked after the creation of model. Let us use an example that shows it. 

  1. Student = Backbone.Model.extend({  
  2. initialize: function () {  
  3. console.log("object is created");  
  4. }  
  5.   
  6. });  
  7.   
  8. var Shriss = new Student(); // new object created  

 When this piece of code is executed, the initialize function will be executed after the model is created. The output of this code in the Chrome console is as:

 

get/set in Model

model.get(attribute)

If we wish to get the current value of the model, we use get to get it. 

  1. Employee = Backbone.Model.extend({  
  2.   
  3. defaults: {  
  4. name: 'anurag',  
  5. age : 24,  
  6. position : 'BiztalkDeveloper'   
  7. },  
  8.   
  9. });  
  10. var Shriss = new Employee(); // new object created  
  11.   
  12. console.log( Shriss.get('name')); // will display the name  
  13. console.log( Shriss.get('age')); // will display the age  
  14. console.log( Shriss.get('position')); // will display the position  

 When we open this in the Chrome console:

 

We can't do: 

  1. Shriss.name // this is invalid  
  2. Shriss.age // this is invalid  
  3. Shriss.age // this is invalid  

set
model.set(attributes, [options])

Whenever we want to update the change in the model we use set. We can keys and values to the set. It sets a hash of attributes on the model. An event will be triggered on the model after changing the attributes of the model. 

  1. Shriss.set('name''shridhar'// this will update the name  
  2. Shriss.set('age',30 ) // update the age  
  3. Shriss.set('position''DotNetDeveloper'// will update the position  

We can set the values in one go as well. 

  1. var Atul = new Employee({ name: 'shridhar', age: 30, position: 'DotNetDeveloper' }); // set                                                                                                                                                                                                                                                           
  1. var Shriss = new Employee(); // new object created  
  2. // Shriss.set('name', 'shridhar');  
  3. console.log( Shriss.get('name')); // will display the name  
  4. console.log( Shriss.get('age')); // will display the age  
  5. console.log(Shriss.get('position')); // will display the position   

 

  1. var Atul = new Employee({ name: 'shridhar', age: 23, position: 'DotNetDeveloper' }); //set    
  2. console.log(Atul.get('name')); //geting     
  3. console.log(Atul.get('age'));    
  4. console.log(Atul.get('position'));   
 
Defaults
model.defaults

To specify the default attributes for the model, the defaults hash (or function) can be used. The default values of the unspecified attributes are set at the time of declaration of the model. 

  1. Student = new Backbone.Model.extend({  
  2.   
  3. defaults:  
  4.   
  5. {  
  6. name: 'shridhar',  
  7.   
  8. age: 24,  
  9.   
  10. designation:'developer'},   
  11. });  

toJSON

model.toJSON([options])

It returns the model attributes for JSON stringification. It serializes an object or is for the augumentation before being sent to the server. In otherwords, this will simply return a copy of the current attributes. This is done by model.toJSON() as well. 

  1. var Student = new Backbone.Model({  
  2.   
  3.   
  4.   
  5. name: "shridhar",  
  6.   
  7. age: 23,  
  8.   
  9. designation:"developer"  
  10.   
  11. });  
  12.   
  13. Student.set({ salry: 20000 });  
  14. console.log(JSON.stringify(Student));  

 Let's check it in the Chrome console.


Attributes
model.attributes

The Attributes property of the model contains the model state, it is an internal hash function. It is a form of JSON object that represents model data on the server. We can use the set property to update the attributes.

Destroy
model.destroy([options])

I have already described destroy in my previous article. I will again strongly recomend that you go through my previous article. If the size of the method is slightly heavier then it takes time to delete the model. In this case we are not quite sure about the response, whether the method is called successfully or not.

  1. Shriss.destroy({  
  2. success: function () {  
  3. alert("The model has been destroyed successfully");  
  4. }  
  5. });  

Let's move over to the Chrome console.

 
Summary

In this article, we are at least in a position to put a step of code into the world of the Backbone.JS model. In articles to come I will definately let you know about the other modules of Backbone.JS.

Words of queries and response are welcome.

Happy Coding!

Up Next
    Ebook Download
    View all
    Learn
    View all