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.
- <!DOCTYPE html>
- <html xmlns="http://www.w3.org/1999/xhtml">
- <head>
- <title></title>
- <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script>
- <script type="text/javascript" src="http://ajax.cdnjs.com/ajax/libs/underscore.js/1.1.4/underscore-min.js"></script>
- <script type="text/javascript" src="http://ajax.cdnjs.com/ajax/libs/backbone.js/0.3.3/backbone-min.js"></script>
- </head>
- <body>
- <script type="text/javascript">
-
- </script>
-
- </body>
- </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:
- Student = Backbone.Model.extend({
-
- });
Instantiating Model
A Model is instantiated using the "new" keyword as:
- var model = new Backbone.Model.extend();
You can also do it using a custom type. Here is how it is:
- Student = Backbone.Model.extend({
-
- });
-
- 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.
- Student = Backbone.Model.extend({
- initialize: function () {
- console.log("object is created");
- }
-
- });
-
- var Shriss = new Student();
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.
- Employee = Backbone.Model.extend({
-
- defaults: {
- name: 'anurag',
- age : 24,
- position : 'BiztalkDeveloper'
- },
-
- });
- var Shriss = new Employee();
-
- console.log( Shriss.get('name'));
- console.log( Shriss.get('age'));
- console.log( Shriss.get('position'));
When we open this in the Chrome console:
We can't do:
- Shriss.name
- Shriss.age
- Shriss.age
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.
- Shriss.set('name', 'shridhar')
- Shriss.set('age',30 )
- Shriss.set('position', 'DotNetDeveloper')
We can set the values in one go as well.
- var Atul = new Employee({ name: 'shridhar', age: 30, position: 'DotNetDeveloper' });
- var Shriss = new Employee();
-
- console.log( Shriss.get('name'));
- console.log( Shriss.get('age'));
- console.log(Shriss.get('position'));
- var Atul = new Employee({ name: 'shridhar', age: 23, position: 'DotNetDeveloper' });
- console.log(Atul.get('name'));
- console.log(Atul.get('age'));
- 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.
- Student = new Backbone.Model.extend({
-
- defaults:
-
- {
- name: 'shridhar',
-
- age: 24,
-
- designation:'developer'},
- });
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.
- var Student = new Backbone.Model({
-
-
-
- name: "shridhar",
-
- age: 23,
-
- designation:"developer"
-
- });
-
- Student.set({ salry: 20000 });
- 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.
- Shriss.destroy({
- success: function () {
- alert("The model has been destroyed successfully");
- }
- });
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!