Marketing Portal

Backbone.js

By Gordon Clark, Ben Wu

Agenda

  • What is backbone?
  • Why backbone?
  • What are the components of backbone?
  • Backbone forms.

What is backbone.js?

  • Backbone.js is a framework for javascript.
  • Modularizes javascript code in a way that makes sense.
  • Gives functionality that makes rendering single page websites easy.
  • Assists with binding and removing javascript events.
  • Has dependency on a library called underscore.js.

Agenda

  • What is backbone?
  • Why backbone?
  • What are the components of backbone?
  • Backbone forms.

Why Backbone?

  • Lightweight framework, 18 KB minified. Angular is 77 KB.
  • Does little to restrict you.
  • De facto javascript framework. Used By:

Agenda

  • What is backbone?
  • Why backbone?
  • What are the components of backbone?
  • Backbone forms.

Router

  • Responsible for responding to changes in the URL.
  • Typically removes and replaces the largest components on the page.
  • Single page website works around this component.

Initial Page


<article>
    <div class="container-fluid">
        <div class="row-fluid">
            <nav id="sub_menu" class="span3">
            </nav><!--/span-->
            <section id="content" class="span9">
       
            </section>
        </div>
    </div>
    <hr>
</article>
<script>
C('global');
$(function() {
    C.global.pageObject = new C.Router.Sample();
});
</script>
                    

Router


C.utility.backbone('Router.Sample')(C.Backbone.Router.extend({
    // Routes is a key-pair value array/JSON that indicate
    routes: {
        "": "home",
        "alias": "alias",
        'form' : 'form'
    },
   // Executes everytime class is instantiated, similar to a constructor.
    initialize: function () {
        ...
    },
    // Callbacks for router.
    home: function () { ... },
    alias : function() { ...  },
    form : function() { ... }
}));
                    

Models

  • At heart, just key-pair values.
  • Triggers events when anything change.
    modelInstance.set('name', 'Gordon'); //triggers 'name:change' event
  • Has additional utilities, such as connecting to restful APIs and performing validations

Views

  • Modularized code that represents a DOM element.
  • Model often used, but not required.
  • Handles events, renderings, communication with model and any other logic related to the DOM element.
  • Misleading name, as it contains logic, can be thought of as being similar to a controller.

Initial Page


<article>
    <div class="container-fluid">
        <div class="row-fluid">
            <nav id="sub_menu" class="span3">
            </nav><!--/span-->
            <section id="content" class="span9">
       
            </section>
        </div>
    </div>
    <hr>
</article>
<script>
C('global');
$(function() {
    C.global.pageObject = new C.Router.Sample();
});
</script>
                    

Menu View


C.utility.backbone('Router.Sample')(C.Backbone.Router.extend({
    ...
    initialize: function () {
        var menuModel = new C.Backbone.Model({
            menuData : [{
                    subtitle : 'sub-menu',
                    links : [{title:'Home Page', href:''},{title:'Alias Page', href:'alias'}]
            },{
                    links : [{title:'Backbone form', href:'form'},{title:'Alias Page 2', href:'alias2'}]
            }]
        });
        this.menuView = new C.View.Menu({el:'#sub_menu', model:menuModel});
        this.menuView. render();
    });
   ...
}));
C.utility.backbone('View.Menu')(C.Backbone.View.extend({
    menu: _.template('<div class="well sidebar-nav">' +
            '<ul class="nav nav-list">' +
            '</ul>' +
          '</div>'),
    subtitle : _.template('<li class="nav-header"><%= subtitle %></li>'),
    item : _.template('<li><a href="#<%- href %>"><%= title %></a></li>'),
    divider : _.template('<li class="divider"></li>'),
    initialize: function () {
        Backbone.history.on("route", function() {
            this.autoHighlights();
        }, this);
    },
    autoHighlights: function() { ... },
    render: function () {
        $(this.el).html(this.menu());
        var ul = $(this.el).find('ul');
        var self = this;
        _.each(this.model.get('menuData'), function(data) {
            if(!_.isEmpty(data.subtitle)){
                ul.append(self.subtitle(data));
            }
            else{
                ul.append(self.divider());
            }
            _.each(data.links, function(data) {
               ul.append(self.item(data)); 
            });
        });
       
        return this;
     }
     ...
}));
                    

Agenda

  • What is backbone?
  • Why backbone?
  • What are the components of backbone?
  • Backbone forms.

Backbone Forms

  • Third party tool:https://github.com/powmedia/backbone-forms.
  • Just an extended view which inherits Backbone.View, but with a few additional functions: getValue, setValue and commit.
  • Provided a schema in a Backbone model, will render a form with the schema.

Backbone Forms


form : function(){
        //Main model definition
        C.utility.backbone('Model.User')(C.Backbone.Model.extend({
            schema: {
                title:      { type: 'Select', options: ['', 'Mr', 'Mrs', 'Ms'] },
                name:       'Text',
                email:      { validators: ['required', 'email'] },
                birthday:   'Date',
               notes:      { type: 'List' },
                weapons:    { type: 'List', itemType: 'Object', subSchema: {
                    name: { validators: ['required'] },
                    number: 'Number'
                }},
                search : {type:'Search'}
            }
        }));

        var user = new C.Model.User({
            title: 'Mr',
            name: 'Ben He Wu',
            email: 'ben@chegg.com',
            birthday: new Date(1982, 12, 30),
            ...
            weapons: [
                { name: 'Uzi', number: 2 },
                { name: 'Shotgun', number: 1 }
            ]
        });
        //The form
        var form = new C.Backbone.Form({
            model: user
        });
        form.render();
        $('#content').html(form.el);
    }
                    

Conclusion

  • Backbone.js brings order to the chaotic nature of javascript.
  • Awesone tools like backbone-forms can lead to rapid development.
  • The documentation is concise, with many examples and can be found at http://backbonejs.org/

THE END

BY Gordon Clark, Ben Wu