Introduction to Backbone JS

Topics

 

  1. Introduction
    • what is backbone JS
    • what is MVP
    • Single Page Application
    • why do we need backbone JS         
  2. Backbone Model
    • ​overview 
    • methods and properties 
    • sample code 
    • quick demo 
  3. Backbone View
    • overview
    • methods and properties
    • sample code
    • quick demo
  4.  


  5. ​​ Backbone Collection 
    • overview
    • methods and properties
    • sample code
    • quick demo
  6. Backbone event
    • overview
    • methods and properties
    • sample code
    • quick demo
  7. Backbone routing 
    • overview
    • methods and properties
    • sample code
    • quick demo

Introduction

What is Backbone JS

 

  • Backbone.js is a JavaScript library with a RESTful JSON interface and is based on the model–view–presenter (MVP) application design paradigm.
  • Backbone is known for being lightweight, as its only dependency is on one JavaScript library Underscore.js
  • UndercoreJS is a javascript library which provides utility functions for common javascript tasks.
  •  It is designed for developing single-page web applications,and for keeping various parts of web applications (e.g. multiple clients and the server) synchronized.

What is MVP

  • Model-view-presenter (MVP) is a derivative of the MVC design pattern which focuses on improving presentation logic
  • Presenter component contains the user interface business logic for the view.
  • The presenter acts as a mediator which talks to both the view and model, however both of these are isolated from each other
  • Make it very easy to handle complex views and user interaction where MVC may not fit the bill.
  • Simplify maintenance greatly 

​​

Single Page Application(SPA)

  • A web application or websites that fits on single web page.
  • Fluid user experience close to a desktop application 
  • Navigation is performed by changing the state
  • In SPA all the necessary codes like HTML, CSS and javaScript are retrieved in a single page load; or resources are loaded on demand without reloading the page at any time

​​

Why SPA?

  • Capable of decreasing subsequent load time of pages by storing the functionality once it is loaded the first time.
  • Achieve a complex user interface without any interaction with server.
  • very interactive and data driven dashboards
  • Event driven application

Why do we need BackboneJS?

 

  • Decouple the DOM from your page's data
  • Allow code to be structured modularly  
  • Provides set of tools for introducing structure in client side javascript application
  • Designed more towards consuming RESTful web service
  • Very easy to implement complex user interaction
  • Free to use any javascript template engine
  • Minimalistic library, has very small footprint 

​​

Backbone Model

Overview 

 

  • Part of your code that retrieves and populates the data
  • The basic data object in the framework -- representing a row in a table in a database on you server 
  • Model can contain application state, as well as logic and behavior.
  • Most of the concepts involved in your application will be represented as models and will contain your application's data
  •  Backbone model go through a series of changes (validation and sync), they communicate state of changes to your application by raising events.

Methods and Properties 

 

 

  • .attributes : ​ The attributes property is the internal hash containing the model's state
  • .isNew:  check to see whether the model is saved
  • toJSON: Return a shallow copy of the model's attributes for JSON stringification.
  • .set & .get: `set` a hash of attributes (one or many) on the model and `get` fetch property from model
  • .validate: developers are encouraged to override it with your custom validation logic
  • .defaults: The defaults hash (or function) can be used to specify the default attributes for your model.
  • .fetchResets the model's state from the server by fetching the data
  • .save : Save a model to your database (or alternative persistence layer), by delegating to `backbone.sync`
  • .destroy : Destroys the model on the server by delegating an HTTP DELETE request to `backbone.sync`
  • urlRoot : Specify a urlRoot if you're using a model outside of a collection

 

Sample Code

var Task = Backbone.Model.extend({
       
         defaults:{ // defaults properties set the default value to the attributes while model instance is created
            name:''
         },
         validate:function(attr){  //validate is place holder method implement in backbone model which need to be overridden 
                if(attr.name.trim().length < 0){    // validate method is called while model is tried to have it
                         return "task need to have valid name";  
                 }
             }
       });



// example 
var task_model = new Task();

//set attributes values 

task_model.set("name","pick up the cat food"); // set method should be used while change the value of attributes 

console.log(task_model.get("name")); // use get method to access the attribute value 

console.log(task_model.attributes); // prints out the attribute object



 

                      Demo

Backbone Collection

Overview

 

  • Collections are ordered sets of models.
  • You can bind "change" events to be notified when any model in the collection has been modified, listen for "add" and "remove" events, fetch the collection from the server, and use a full suite of Underscore.js methods.
  • Any event that is triggered on a model in a collection will also be triggered on the collection directly, for convenience.
  • This allows you to listen for changes to specific attributes in any model in a collection.

Methods and Properties 

 

 

  • .models : ​ Raw access to the JavaScript array of models inside of the collection
  • .where :  Return an array of all the models in a collection that match the passed attributes
  • .add and .remove : `.add` a model (or an array of models) to the collection, firing an "add" event and '.remove' a model (or an array of models) from the collection.
  • .at: Get a model from a collection, specified by index.
  • .sort: Force a collection to re-sort itself.
  • .reset : Use reset to replace a collection with a new list of models
  • .fetchFetch the default set of models for this collection from the server
  • .create : Convenience to create a new instance of a model within a collection
  • .toJSON: Return an array containing the attributes hash of each model in the collection.
  • url: Set the url property  on a collection to reference its location on the server. 

 

Sample Code



var TaskCollection = Backbone.Collection.extend({
    model : Task,
    url: '/tasks'
});


var task_collection = new TaskCollection();


task_collection.add(new Task({name:"pay bills"}));

task_collection.create(new Task({name:"pay bills"}); // add 


console.log(task_collection.models); // attributes holds the list of task model

console.log(task_collection.toJSON()); // convert all the models in collection into json

console.log(task_collection.at(1)); // gets the model at index 1

Demo

Backbone View

Overview

 

 

  • Views in backbone does not contain the markup for your application
  • Support models by defining the logic for how they should be represented to users
  • Markup for views is provided by the templates defined and rendered with template engine like underscore or handlebar etc.
  • The general idea is to organize your interface into logical views, backed by models, each of which can be updated independently when the model changes, without having to redraw the page
  • View automatically update or re-render on change or update, by just binding the model or collection event with view render method 

 

 

Methods and Properties 

 

 

  • .el : ​ All views have a DOM element at all times (the el property), whether they've already been inserted into the page or not
  • .render:  Override this function with your code that renders the view template from model data, and updates `this.el` with the new HTML
  • .events: is a object where the key is of the form event name  css selector” and value side of each property is the name of the event handler function 
  • .attributes: A hash of attributes that will be set as HTML DOM element attributes on the view's el(id, class, data-properties, etc.)

Sample Code 

var list_view = Backbone.View.extend({
                  tagName:'li', // tag to be generated while the view is rendered

                  template:_.template("<span><%= name %></span><span class='remove'>Remove</span>"),
                  events:{
                   'click .remove':'remove_task' // binding remove span with click to remove the view on click
                  },  
                  render:funcntion(){   // a placeholder which has to be overridden by develop to render the content
                  
                   this.$el.html(template(this.model.toJSON());
                   return this;

                  },
                 remove_task:function(e){
                        this.remove(); // removing the view self from display or html dom tree
                 },

                });


var form_view = Backbone.View.extend({
                el:'#todoform',
                events:{
                'click button#add':'add_task'
                },
                add_task:function(e){ 
                   this.collection.add((new Task()).set("name",this.$el.find('input#taskname').val()));
                }
    
                });


var list_item = new list_view(); // creating a instance of list view 

console.log(list_item.render().el);

var form_view = new form_view();

console.log(list_item.el);

Demo 

Backbone Events

Overview

 

 

  • Events is a module that can be mixed in to any object, giving the object the ability to bind and trigger custom named events. 
  • Events do not have to be declared before they are bound, and may take passed arguments.
  • All the components views, models and collections use Events module internally to bind and trigger events

Methods and Properties 

 

 

  • .trigger : ​ Trigger callbacks for the given event
  • .on:  Bind a callback function to an object.
  • .off: Remove a previously-bound callback function from an object.
  • .listenTo: `Tell an object to listen to a particular event on an other object
  • .stopListening: Tell an object to stop listening to event                                                                           

Sample Code

 // using the underscore extend method to mix regular object to backbone event object 


var Event_Aggregator = _.extend({},Backbone.Events);



// example implementation 

(function(){

    Event_Aggregator.on("random_name",function(mesg){

       alert(mesg);
    });

})();

Event_Aggregator.trigger("random_name","say hello to the group");


// using this in backbone in demo

Demo

Backbone Routes

Overview

 

 

  • Routes are used to help manage application state and connecting URL to application events.
  • hash fragments (#page) were used to provide these permalinks, but with the arrival of the History API, it's now possible to use standard URLs (/page). Backbone.
  • Router provides methods for routing client-side pages, and connecting them to actions and events.
  • For browsers which don't yet support the History API, the Router handles graceful fallback and transparent translation to the fragment version of the URL.
  • During page load, after your application has finished creating all of its routers, be sure to call Backbone.history.start(), to route the initial URL.

                                                        

Methods and Properties 

 

 

  • .routes : ​ hash maps with URLs with parameters to functions on your router
  • .navigate:  method is basically how you redirect to other locations in your Backbone application
  • .routeManually create a route for the router,The route argument may be a routing string or regular expression.

 

Sample Code

var Router = Backbone.Router.extend({
              routes:{
                "":"home",
                "about","about"
              },
             home:function(){

               // my code to display on home page 

             },
             about:function(){
                      // my code to display about page
             }
             });



var my_application_routes = new Router(); // create instance of route

console.log(my_application_routes); 

Demo

References 

References 

  • http://backbonejs.org/
  • http://code.tutsplus.com/tutorials/getting-cozy-with-underscorejs--net-24581
  • http://backbonetutorials.com/
  • http://www.codebeerstartups.com/2012/12/introduction-to-backbone-js-and-setting-up-an-working-environment/
  • http://code.tutsplus.com/tutorials/getting-started-with-backbonejs--net-1975
  • https://www.youtube.com/watch?v=FZSjvWtUxYk
  • http://coenraets.org/blog/2011/12/backbone-js-wine-cellar-tutorial-part-1-getting-started/

Thank you 

Thank you 

Sponsorers

Made with Slides.com