Subscribe via RSS Feed

Models in Backbone.js

April 16, 2014 6 Comments

Introduction:
working on a web application involves a lot of JavaScript.in backbone we use models as representative of the information. as we can create, update, delete,validate and also store the data/information in server. we are able to do the same things with a model in backbone.an UI action causes an attribute of a model to change, the model triggers a “change” event; all the Views that display the model’s state can be notified of the change, so that they are able to respond accordingly, re-rendering themselves with the new information. Backbone is an attempt to discover the minimal set of data-structuring and user interface primitives that are generally useful when building web applications with JavaScript.

models:
Models are the heart of any JavaScript application, containing the interactive data as well as a large part of the logic surrounding it:conversions, validations, computed properties, and access control. there are two types of models, Thread and Message.a Thread being able to contain multiple Messages.

Message Model:

$.forum.Message = Backbone.RelationalModel.extend({
    urlRoot: '/api/message',
    idAttribute: '_id',
});

The Message model is the most simple model structure.in the above code snippet we’re extending Backbone.RelationalModel rather than BackboneModel. With this process we can take advantage of the extra features of Backbone-relational. We’re notifying Backbone via urlRoot the address of corresponding resource on the server.with the value of idAttribute the server can uniquely identify each message.

Thread Model:

$.forum.Thread = Backbone.RelationalModel.extend({
    urlRoot: '/api/thread',
    idAttribute: '_id',
    relations: [{
        type: Backbone.HasMany,
        key: 'messages',
        relatedModel: '$.forum.Message',
        reverseRelation: {
            key: 'thread',
            includeInJSON: '_id',
        },
    }]
});

The relations option we are using comes from Backbone-relational.

It allows to specify how the Thread objects relate to the Message objects:

type: Backbone.HasMany: Each Thread can contain references to multiple Messages.
key: ‘messages’: The name of the attribute of Thread objects containing the external references. Thread.messages will contain an array of Messages.
relatedModel: ‘$.forum.Message’: The model being referenced.
reverseRelation.key = ‘thread’: The reverse reference to the Thread object, from each of the Message objects contained.
reverseRelation.includeInJSON = ‘_id’: Tells Backbone-relational to store the value of one of the Thread attributes in message.thread, rather than a reference to the object itself.
In the above we saw a few types of models used in backbone. Now let us go through the models to discuss the operations of models.

In the following we can see the relationship of model and other components of backbone:

model

Creating a model:
As we have mentioned earlier, that we represent our data as models in backbone. So, at first we will discuss the creation process of the models. If we wish to create a new user on the server then we will instantiate a new User and call save. If the id attribute of the model is null, Backbone.js will send a POST request to the urlRoot of the server.

var User = Backbone.Model.extend({
        urlRoot: '/user',
        defaults: {
            name: '',
            email: ''
        }
    });
    var user = new User ();
    // Notice that we haven't set an `id`
    var userDetails = {
        name: 'name',
        email: ‘[email protected]’
    };
    // Because we have not set a `id` the server will call
    // POST /user with a payload of {name:' name ', email: ‘[email protected]’}
    // The server should save the data and return a response containing the new `id`
    user.save(userDetails, {
        success: function (user) {
            alert(user.toJSON());
        }
    })

Updating a model:
as we update any data according to our needs in a web application. In backbone we are allowed to do so with the models too. Now that we have a model that exist on the server we can perform an update using a PUT request. We will use the save api call which is intelligent and will send a PUT request instead of a POST request if an id is present.

// Here we have set the `id` of the model
    var user = new User ({
        id: 1,
        name: 'name',
        email: ‘[email protected]’
    });
    // Let's change the name and update the server
    // Because there is `id` present, Backbone.js will fire
    // PUT /user/1 with a payload of `{name: 'Arjun', email: ‘[email protected]’}`
    user.save({name: ' Arjun '}, {
        success: function (model) {
            alert(user.toJSON());
        }
    }); 

Deleting a model:
In the above we have created a model, updated the name attribute of that model. Now we are going to see the process of deleting the same model. we know our model has an id that exist on the server, so if we wish to remove it from the server we can call destroy(). destroy will fire off a DELETE /user/id.

  // Here we have set the `id` of the model
    var user = new User ({
        id: 1,
        name: 'name',
        email: ‘[email protected]’
    });

    // Because there is `id` present, Backbone.js will fire
    // DELETE /user/1 
    user.destroy({
        success: function () {
            alert('Destroyed');
        }
    });

Without creating, updating and deleting. We can do many changes to the models. We are going to discuss about those changes now.

Setting attributes in model:
We have created model. Now we want to pass some parameters when we create an instance of our model. In this code snippet we can see that we are passing values as parameter in time of initialization. passing a JavaScript object to our constructor is the same as calling model.set().

    User = Backbone.Model.extend({
        initialize: function(){
            alert("Hello!");
        }
    });
        var user= newUser({ name: "name", age: 24});

Getting attributes of model:
In the previous example we have set the value of a model named ‘user’. There will be many times where we want to try retrieve the values of models. There is an easy process to it, we are going to discuss this method now. Using the model.get() method we can access model properties at anytime.

User = Backbone.Model.extend({
        initialize: function(){
            alert("Hello!");
        }
    });
       var user = new User({ name: "name", age: 24});
      var age = user.get("age"); // 24
    var name = user.get("name"); // "name"

Setting model defaults:
Sometimes we want that our model should have default values, so that they can stay constant. This can easily be accomplished by setting a property name ‘defaults’ in model declaration.

User = Backbone.Model.extend({
        defaults: {
            name: 'BMW',
            model:i8,
            type:’car’
        },
        initialize: function(){
            alert("Hello!");
        }
    });
        var user = new User({});

Manipulating model attributes:
Sometimes we will feel the need to create custom methods. Models can contain many custom methods to manipulate attributes. By default all methods are public.

    User = Backbone.Model.extend({
        defaults: {
            name: 'BMW',
            model:i8,
            type:’car’
        },
        initialize: function(){
            alert("Hello!");
        },
        buy: function( newCarsName ){
            this.set({car: newCarsName });
        }
    });
     var user = new User({name: 'BMW',model:i8,type:’car’});
user. buy (‘Porsche’);
    var car = user.get("car"); // ‘Porsche’

So we can implement methods to get/set and perform other calculations using attributes from our model at any time.

Listening for manipulations in the model:
Now onto one of the more useful parts of using backbone. All attributes of a model can have listeners bound to them to detect changes to their values.

    User = Backbone.Model.extend({
        defaults: {
name: 'BMW',
            model:i8
        },
        initialize: function(){
            alert("My Car");
            this.on("change:name", function(model){
                var name = model.get("name"); // ‘Porsche’
                alert("Changed my car’s name to " + name );
            });
        }
    });

    Var user = new User({name: 'BMW',model:i8});
    user.set({name: ‘Porsche’}); 

So we can bind the change listener to individual attributes or if we like simply ‘this.on(“change”, function(model){});’ to listen for changes to all attributes of the model.

Retrieving a model:
In the above we have created a model and used it in various ways. But we never retrieved the model from server. We can retrieve it from the server. We know that the id is 1 from the above example. If we instantiate a model with an id, Backbone.js will automatically perform a get request to the urlRoot + ‘/id’.

    var user = new User ({id: 1});
    user.fetch({
        success: function (user) {
            alert(user.toJSON());
        }
    })

Conclusion:
In the above article we have discussed about model. Model is an important feature in backbone.js. we have tried to understand it’s many different applications as well as to use them. We always have to remember that in backbone.js models are used as specific data, so there are many other ways we can manipulate them and use them as we see fit.

Some related articles :

1>Introduction to Backbone.js

2>Understanding view in Backbone.js

3>Underscore Methods in Backbone.js

4>Backbone Routes and History

5>Collections in Backbone.js

6>Templates In Backbone.js

7>WHY SHOULD WE USE SERVER SIDE IN BACKBONE.JS?

8>Backbone.js at a glance

We will have other detail of Backbone features in our later articles. So please look for the same.
If you find this article helpful, you can connect us in Google+ and Twitter.

Sign Up to read the rest of the content

Email will be used only for updates of our site

No Thanks