Models in Backbone.JS

Introduction

This article explains Models in Backbone.JS. Backbone.JS is a JavaScript framework for creating web applications. It is gaining in popularity in the web application community among the other frameworks. It uses the structure given by JavaScript.

Backbone follows the pattern MV* (Model View). In other words, the model contains the interactive data and logic of this data. We use a model in Backbone to represent the concept of the object using its attributes. The view of the Backbone not only works as a view but also works as a controller for connecting the model to the data interaction.

There is a different concept in Backbone in which one is the Model. So now we learn about the Model in Backbone.

Model

A Model in Backbone consists of the connected data for the web application. It also contains the connection among the data. We use the models for representing the concept of the object including its attribute. When we create a model it's extended from the "Backbone.Model".

Here we provide sample code for creating the Model. We use a Model representing an image object such as title, location (src) and so on.

var Photo = Backbone.Model.extend({

    defaults: {

      src: 'placeholder.jpg',

        title: 'Image',

        coordinates: [0, 0]

    },

    initialize: function () {

        this.on("change:src"function () {

            var src = this.get("src");

            console.log('Source ' + src);

        });

    },

    changeSrc: function (source) {

        this.set({ src: source });

    }

});

var somePhoto = new Photo({ src: "Koala.jpg", title: "Pic" });

somePhoto.changeSrc("Desert.jpg"); // which triggers "change:src" and logs an update message to the console.

 

In the code above there is an initialize() method, it is invoked when a new instance is created. The use of it is optional.

Attributes of the Model. There are various types of attribute accessing methods that are used by the Model.

  • Model.get()
  • Modet.set()
  • Default Values
  • Validation

Model.get():

Model.get() provides an easy way to access the attributes. The attributes passed to the model at the time of instantiation that are ready to be fetched.

var Image = new Photo({

    title: "This is pic",

    src: "Desert.jpg",

    location: "esert",

    tags: ['the big game''vacation']

}),

 title = Image.get("title"), //This is pic

 location = Image.get("location"), //Desert

 tags = Image.get("tags"), // ['the big game','vacation']

 photoSrc = Image.get("src"); //Desert.jpg

 

If you want to access all the attributes of the model directly then you can use this:

var attrib = Image.attributes;

console.log(attrib);

It is the best way to to use Model.get() or direct instantiation for setting the attribute's value of the model.

Model.set():

The Model.set() is used for passing the instance attribute of the model. We can pass the attribute at the time of the initialization or after that.  One important thing is that we need to avoid is to set the attribute of a Model directly such as Model.Image="A different Image". Backbone uses the Model.set() for setting the attribute of the model.

var Photo = Backbone.Model.extend({

    initialize: function () {

        console.log('The initialization of the model');

    }

});

// Setting the value of attributes via instantiation

var Image= new Photo({ title: 'My Image', location: 'Desert' });

var Image2 = new Photo();

// Setting the value of attributes through Model.set()

Image2.set({ title: 'Winter vacation in Rajasthan', location: 'Rajasthan' });

Default values:

There are times that we want to set the default values for the model. Then we use the default property to set the default value of the model. It is used when the user does not provide the complete data in any scenerio.

defaults:{

 

        title: 'Writer Image',

        tags: ['untagged'],

        location: 'office',

        src: 'Pic.jpg'

},

initialize: function(){

    var myPhoto = new Photo({ location: "Desert"

        tags:['the big game''vacation']}),

     title = myPhoto.get("title"), //Writer Image

     location = myPhoto.get("location"), //Desert

     tags = myPhoto.get("tags"), // ['the big game','vacation']

     photoSrc = myPhoto.get("src"); //Pic.jpg

Validation:

Backbone uses the Model.validation() for supporting the model validation. It is especially used for checking the value of the attribute that is properly set to the model. It can be simple or complex depending on needs. If the providing attributes are valid then there is nothing returned from Validation, otherwise it is invalid and then it will return an error message.


Similar Articles