Backbone.js Overview

Overview of Basic Backbone.js Concepts

View the Project on GitHub heme/backbone-example

Backbone.js Concepts

Backbone.js provides structure to web applications in 4 ways...

  1. Models & Collections (Data Structures)
  2. Event System (Subscribe & Trigger)
  3. Views (Controls Data & Templates)
  4. Routers (Application State in URL)

1. Models & Collections

Create a Model:
    // Model
    var Employee = Backbone.Model.extend({
      urlRoot: '/employee/'
    });

    var employee = new Employee();
Create a Collection:
    // Collection
    var Employees = Backbone.Collection.extend({
      url: '/employee',
      model: Employee
    });

    var employees = new Employees();

2. Event System

Listen to a Model:
    // create an instance of the employee model
    var newHire = new Employee();

    // create a generic JavaScript object and add a function to it
    var im_listening = {};
    im_listening.processData = function() {
        alert('The new employee's name is: ' + newHire.get('FirstName') + newHire.get('LastName'))
    };

    // extend the generic JavaScript object with Backbone.js's event object
    _.extend(im_listening, Backbone.Events);

    // tell our object to listen to the model's sync event
    im_listening.listenTo(newHire, 'sync', im_listening.processData);

    // fetch data for that model from API, will trigger the "sync" event
    newHire.set('id',136);
    newHire.fetch();

3. Views

Create a View:
    // View - Detail
    var EmployeeDetailView = Backbone.View.extend({
        events: {
            'click #btnLoad': 'loadEmployee'
        },
        el: '#employeeViewContainer',
        initialize: function() {
            this.model = new Employee();
            this.listenTo(this.model, 'sync', this.render);
        },
        loadEmployee: function() {
            var id = this.$('#employeeID').val();
            this.model.set('id', id);
            this.model.fetch();
        },
        render: function () {
            var name = this.model.get('FirstName') + ' ' 
                + this.model.get('LastName');
            this.$('#employeeName').html(name);
        }
    });

    var employeeDetailView = new EmployeeDetailView();
#employeeViewContainer ID: Load

 

4. Routers

    // Application Router
    var Router = Backbone.Router.extend({
        routes: {
            // 'URN in address bar' : 'function on this object to call when URL matches'
            '': "index", // http://application.com/
            'employee/:id': 'employee' // http://application.com/employee/6
        },
        index: function() {
            var employeeListView = new EmployeeListView();
        },
        employee: function(id) {
            var employeeDetailView = new EmployeeDetailView({'id':id});
        }
    });