Backbone.js: MVC framework for Javascript – Models

Posted on July 30, 2012

7


There are many MVC frameworks for Javascript. Spine.js and Backbone.js are most famous and used of all. But we’ll be seeing only Backbone.js here only.

Before that, spine is fundamentally different from backbone. Spine strictly follows MVC model, while there is actually nothing like Views in backbone conceptually. Plus there is no controller either in backbone, C stands for collection.

So, model is model+controller, and controller is views in backbone. Backbone also uses Underscore.js as helper for collections. So, we need both underscore and backbone for the application while spine is used alone.

We will start with models first. Model have numerous methods to perform various operations. The example are based on ajax requests, instead of CRUD operations using REST API. We’ll get back to those later. Its not that complicated just lets get started with what we know already.

Requirement: Backbone.js ( + Underscore.js ), jQuery.js ( latest )

Usage:

/*
* Backbone model should have everything which is interacting with your database.
* A user model can be implemented by extending backbone's existing model and its methods.
*/
var book = new Backbone.Model.extend({
// defaults method holds key-value pair object. These are like class variables. You can set them and use them later.
    defaults: {
        'Title': '',
        'Author': '',
        'Publisher': '',
        'ISBN_No': 0
    },

/*
* fetch method by default is associated with url we specify for model but we have overwritten it for now.
* We are using fetch for fetching the data from database.
*/
    fetch: function(){
        var url = 'http://example.com';
        var call = 'getBook';
        var id = '12';

// Ajax call
        $.ajax({
            url: url,
            type: 'GET',
            dataType: 'JSON',
            data: {'call': call, 'id': id},
            success: function(data){
                //Do something with your data using jquery or return some html from the handler.
            }
        });

    },

/*
* save method is used for saving data to database. By default on calling save default url is used to save.
* We have overwritten just for now. Save by itself identify create and update operation for database.
* We will come back to this later
*/
    save: function(){
/*
* this is pointing to the instance which has called save method.
* get method for model will get you the values stored in the variable in defaults of the model's instance.
*/
        var url = 'http://example.com/savebook.php';
        var data = {'title': this.get('Title'), 'author': this.get('Author'), 'publisher': this.get('Publisher'), 'isbn': this.get('ISBN_No')};
        $.ajax({
            url: url,
            type: 'POST',
            dataType: 'JSON',
            data: data,
            success: function(data){
                //Do something when your data get saved in your database.
            }
        });
    },
/*
* When we try to update the defaults or save the model validate methods is called by default.
* It should return nothing if validation succeeds because this method by default returns true;
* In case of fail an error string can be returned as below.
*/
    validate: function(attrs){
        //validation for the values to be saved.
        var error = '';

        if(attrs.ISBN_No == 0)
            error += 'ISBN No cannot be equal to 0';
        if(error != ''){
             return error;
        }
    }
});

Explanation:

Everything is explained in comments. Also go through the methods associated with model here.

Hope you like it. It may not seem very intuitive for now. But I think you must have gotten taste for it. We’ll work with Routers in upcoming post.

About these ads