Home » Backbone » Backbone Models

Backbone Models

Welcome to the first module of Backbone.js tutorial. In this Module we will cover some basic concepts of backbone Models, how models can be created and instantiated, how the user can get the data from models and how the data can be changed dynamically. Moving further we will see how models can listen to change events and lastly how can we apply the validation on model data before saving it.

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

  • Defining and instantiating models
  • id,cid
  • isNew
  • Inheritance
  • Setter, getter
  • escape
  • has
  • unset
  • Listening for change model
  • Defaults
  • toJSON
  • Validation
  • Events
  • Server methods

 

Model:

Backbone models play major role in any application UI. Models hold application data and logic to manipulate that data, other than that models can also be used to sync the data and apply the validation. Models can also perform some action on change of their state, like updating Views when the data changes.

Let’s start with simple model creation:

var shapes = Backbone.Model.extend({
               height:'16',
               width:'12'
              },{ // this is the second param of extend which is used to set class properties
                area:function(){
                                console.log("Calculate the area");
                }
             });
var square = new shapes(); // create instance of shapes
square.height = "12" // accessing the attributes and assigning value
console.log("height is "+square.height);

// console: height is 12

var rectangle = new shapes();
console.log(rectangle.height);  

// console: height is 16

shapes.area(); // you can directly call this function (i.e. the second param of extend function), without creating an object

square.area(); // this will throw an error, because area is only available directly on model constructor

Above is the very basic example of creating backbone models which shows how we can create the model instance and get the attribute value

 

Defining and instantiating models

Backbone provides initialize() function which can be used in cases where you want to apply some logic before application starts,  for example if you want to prefill some fields in html form when browser launches the application. In such scenarios you can call initialize() function on your model, which will be called as soon as application loads that model.

var shapes = Backbone.Model.extend({
                 initialize:function(){ // this method will be called as soon as model is loaded
                        console.log("shapes created");
                    }
                });

var square = new shapes();

In above example “square” is an instance of “shapes” model; creating an instance of shapes model will automatically trigger the initialize() method.

 

id,cid

id and cid are the unique id’s of each model. “id” property is created only after model is created, whereas “cid” is a temporary id generated by backbone itself.

cid is only required till the model is not saved, once the model is created “id” property can be used instead of “cid” property.

 var shape= Backbone.Model.extend({

                });

var square= new shape();
console.log(square.id);

// console: will return undefined because the model is not saved.

console.log(square.cid);

// console: c0 // temporary id

 

isNew

isNew() method returns true if the model is newly created or else returns false. In backbone, those models which don’t have “id” property are considered to be new and in that case isNew() method will always return true.

var shape= Backbone.Model.extend({

           });
 var square= new shape();
 console.log(square.isNew());

// console: true

 

Inheritance

Just like OOP (Object Oriented Programming) inheritance, backbone model can inherit properties from its parent model.

// Parent model
var shapes = Backbone.Model.extend({
                area:function(){                                                               
                            return this.get("height") * this.get("width");
                }
});

// Object of shapes model.
var edgeShape = new shapes({
                height:4,
                width:4
});

console.log(edgeShape.area());
// console: 16

Now create a variable (called rectangle)which will extend “shapes” model, this variable will have all the properties of its parent model(i.e. shapes model)

var rectangle = shapes.extend();  // Inheriting the properties of shapes model

// creating an object of rectangle
var mRectangle = new rectangle({
                height:12,
                width:3
});

// calling area() on mRectangle which was defined in its parent model

console.log(mRectangle.area());
// console: 36

 

Setter, getter

In Backbone, you can get and set the values of model attribute by using Model.get() and Model.set() respectively. Let’s check out both the functions one by one.

  • Model.get()

                You can get the value of attribute by passing the attribute key in Model.get() method.

var person = Backbone.Model.extend({
                      defaults:{
                          name:'Himanshu',
                          age:'26',
                           StringfyData :function(){ // this method returns the model as a JSON string.
                                     console.log(JSON.stringify(this));
                            }
                      }          
       });

Above code will create simple model which has one function , StringfyData() (which will return model as a JSON string) and two attributes, name and age. Now to get the the value of any attribute you will have to call get() method on mPerson model.

var mPerson = new person();
console.log(mPerson.get('name')); // getting 'name' attribute value

// console: Himanshu

console.log(mPerson.get('age'));  // getting 'age' attribute value

// console: 26

 

  • Model.set()

                You can set the value of model’s attributes by using Model.set(). There are many ways to set the attribute values. 

1st way:

var personData = new person({name:"HimanshU"}); // you can directly pass key,value pair while creating model object.

 

2nd way:

personData.set("height","6.1"); // you can pass key,value pair in Model.set() method.

 

3rd way:

personData.set({country:"India", sex:"Male"});// you can set multiple key,value pairs by passing them as an object

personData.set("designation","Software Engineer");
personData.StringfyData();

// console:  {"name":"HimanshU","height":"6.1","country":"India","sex":"Male","designation":"Software Engineer"}

           

escape

Model.escape() method is same as get method, the only difference is, escape() method returns HTML escaped value of model’s attribute. Check the below example to get the better understanding of escape() method.

// setting title attribute in person Model
personData.set("title","<script>Person data</script>");

personData.get("title"); // retrieving value using get()

// console: <script>Person data</script>

personData.escape("title"); // retrieving value using escape()

// console: &lt;script&gt;Person data&lt;/script&gt;

 

has

has() method returns true if the model has that attribute or else returns false.

if(personData.has("designation")) // check the property
                             console.log(personData.get("name")+" is a "+personData.get("designation"));

// console: HimanshU is a Software Engineer

 

unset

Like set() method is used to set the model’s attribute value, model.unset() method is used to delete the model’s attribute value

// removing height attribute
personData.unset("height");
personData.StringfyData();

// console: {"name":"HimanshU","country":"India","sex":"Male","designation":"Mobile application developer"}

 

Listening for change model

As discussed earlier that the model’s attribute value can be changed by using Model.set(), but what if you want to update the UI with new value? What if you want to render your HTML with updated values? The answer is by using change event. Whenever you change the model’s attribute value, backbone triggers change event on that model. Below are couple of examples which will show you the importance of backbone change event.

  • Change event within model definition
// creating model
var person = Backbone.Model.extend({
                           defaults:{    
                                 name:'Himanshu', 
                                 age:'26'
                            },
                            initialize: function(){
                                this.on('change', function(){
                                  console.log(JSON.stringify(this));
                                  });
                                }
                       });

//Creating model object
var personData = new person();

// setting model value which will trigger change event on model
personData.set("country","India");

// console: {"name":"Himanshu","age":"26","country":"India"}

 

  • Change event on model object
// creating model
var person = Backbone.Model.extend({
                     name:'Himanshu',
                     age:'26'
                    });

//Creating model object
var personData = new person();

// defining callback function which will be triggered on model state change.
personData.on("change",function(){
                 console.log(JSON.stringify(this));
       });

// setting model which will trigger change event on model
 personData.set("country","India");

//console: {"name":"Himanshu","age":"26","country":"India"}

In above example change event will be triggered if any of the attribute changes.

You can also trigger change event on individual attribute.

var person = Backbone.Model.extend({
                      defaults:{
                             name:'Himanshu',
                             age:'26'
                       },
                       initialize: function(){
                             this.on('change:country', function(){ // Change event will be triggered only if country value changes. 
                                  console.log(JSON.stringify(this));
                               });
                        }
                });

var personData = new person();

// no event will be triggered because you are setting/changing designation not the country.

personData.set("designation","Software Engineer");

// console: will not print anything

// Now the change will be triggered because you are setting/changing the country.
personData.set("country","India");

// console: {"name":"Himanshu","age":"26","country":"India"}

If you don’t want to trigger change event, you can pass {silent:true} as a second parameter in Model.set().

personData.set({"country":"India"},{silent:true});

change in country will not trigger change event because you are passing {silent:true}

 

Defaults

Default is used to provide default value to model’s attributes. This is useful when you do not provide attribute value at run-time; in that case it takes the default value. Default helps in dealing with null value exceptions.

var person = Backbone.Model.extend({
                              defaults:{
                                      date:Date(),
                                      name:'Himanshu',
                                      age:'26'
                                },
                               initialize:function(){
                                  console.log(JSON.stringify(this));
                               }
                });

var personData = new person();              

// console: {"date":"current Date","name":"Himanshu","age":"26"}

 

toJSON

toJSON() method returns the model in form of JSON object. toJSON() method is useful when you want to post some data on server.

var person = Backbone.Model.extend({
                          defaults:{
                                  date:Date(),
                                  name:'Himanshu',
                                  age:'26'
                               }
                });

var personData = new person();              
console.log(personData.toJSON());

// console: Object {date: "current date", name: "Himanshu", age: "26"}<span style="font-size: medium;"> </span>

 

Validation

Validation is one more important concept of backbone models, it helps to perform some check on the attribute value before saving that value, for example, checking the emailID format. You can apply validation check on model attributes by using validate() method, this method returns message if the validation fails.

Validate() method gets called before performing set or save on model.

You should pass {validate:true} while setting the attribute value. 

Below is the model definition with validate method, validate method will check whether the item is allowed to carry or not.

var person = Backbone.Model.extend({
                validate:function(value){
                    // array for restricted items
                    var restrictedAccessories = ["swiss Knife", "lighter", "matchbox"]; 

                   // _.contains check whether the value you have passed is there in restricted array or not and returns true or false.
                    var carryingrestrictedAccessories = _.contains(restrictedAccessories,value.Accessories); 

                  // if true then return message
                  if(carryingrestrictedAccessories)
                         return "Sorry! You can not carry "+ value.Accessories +" with you";                                            
                }
});

var personData = new person({name:"Himanshu"});

// attaching invalid event with model, this will display error message if data is invalid

personData.on('invalid', function(model, errormsg){
                console.log(errormsg);
});

// {validate: true} to trigger validation check on that value.

personData.set("Accessories","swiss Knife",{validate: true});  // fail validation

personData.set("Accessories","Camping stuff",{validate: true}); // pass validation

//console: Sorry! You cannot carry swiss Knife with you

 

Events

Events are one of the major key feature of Backbone.js library, you can register change events for a model to detect the change in its attribute value (as already explained above). Other than using predefined events, backbone gives the freedom to define own custom events also. You can register custom events with the model to get more flexibility.

Custom events can be registered by using on() method. First parameter of on() method is the name of custom event, you can use any name but it is always a good practice to follow proper naming convention. Second parameter of on() method is the callback function which will be called when event triggers. Custom events can be triggered using trigger(eventName).

 // defining model

var person = Backbone.Model.extend({
             });

var personData = new person();

Below code will register custom event for “personData” model by using on() method.

// registering custom event "travelling:onsite"

personData.on("travelling:onsite",function(value){
      console.log("Carry all the necessary items - ",
      value.itemOne+" and "+value.itemTwo);
 });

 

Trigger() method will trigger the custom event. First parameter of trigger() is the name of custom event and second parameter is the set of values that you want to pass to your custom event.

using _.delay will delay the execution of function by 2000ms.

_.delay(function(){
                personData.trigger("travelling:onsite",{itemOne:"Passport",itemTwo:"Visa"})
},2000);

Above code will be triggered after 2000ms and will print below result in console.

// console:  Carry all the necessary items - Passport and Visa.

Server methods

Backbone model provides some methods to interact with server. The same methods can be used with backbone collections also, but its completely your choice how you want to use them.

  • save(): This method is same as post/put method. save() can be used to insert model if it’s not already there on the server or else update the model data if it’s there on server.
  • fetch(): This method is same as get method. This method gets the data from server.
  • destroy(): This method is used to delete existing model from server.

Server Interaction will be covered in details in last module of this tutorial series, if you are curious to learn about server interaction you can directly jump to last module.

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>