SlideShare a Scribd company logo
03 Backbone
Framework Analysis
Public Code Repository




                                                               by
                                          Sergey N. Bolshchikov
                                           http://bolshchikov.net
                         sergey.bolshchikov@new-proimage.com
                                           New ProImage, 2012
Outline
  I.   Introduction

 II.   Dependencies

III.   Components
       a. Model
       b. Collection
       c. View

IV.    Utilities
       a. Router
       b. History

V.     Conclusion
Shortly: 5 things
Backbone.js gives structure to web
applications by providing models with
key-value binding and custom events,
collections with a rich API of
enumerable functions, views with
declarative     event    handling,    and
connects it all to your existing API over
a RESTful JSON interface.
Shortly: 1
Backbone.js gives structure to web
applications by providing models with
key-value binding and custom events,
collections with a rich API of
enumerable functions, views with
declarative     event    handling,    and
connects it all to your existing API over
a RESTful JSON interface.
Shortly: 2
Backbone.js gives structure to web
applications by providing models with
key-value binding and custom events,
collections with a rich API of
enumerable functions, views with
declarative     event    handling,    and
connects it all to your existing API over
a RESTful JSON interface.
Shortly: 3
Backbone.js gives structure to web
applications by providing models with
key-value binding and custom events,
collections with a rich API of
enumerable functions, views with
declarative     event    handling,    and
connects it all to your existing API over
a RESTful JSON interface.
Shortly: 4
Backbone.js gives structure to web
applications by providing models with
key-value binding and custom events,
collections with a rich API of
enumerable functions, views with
declarative    event     handling,   and
connects it all to your existing API over
a RESTful JSON interface.
Shortly: 5
Backbone.js gives structure to web
applications by providing models with
key-value binding and custom events,
collections with a rich API of
enumerable        functions,views    with
declarative     event    handling,    and
connects it all to your existing API over
a RESTful JSON interface.
Dependencies


               Backbone

  Underscore    json2.js   [jQuery]
Backbone Components
Model
Backbone model contains interactive data. It possess different useful properties
and methods:

●   id - modelID
●   idAttribute - databaseID
●   get(attrName) - returns attribute value
●   set(attrName, attrValue) - sets the value for the named attribute
●   clear() - removes all model attributes
●   toJSON() - return a copy of the model's attributes for JSON stringification
●   url - relative URL where the model's resource would be located on the
    server
●   fetch() - gets the latest version of the model from the server
●   save() - saves the model to the DB
●   validate() - checks the given data before set() and save()

P.S. Almost never is predefined
Model
var GreetingModel = Backbone.Model.extend({
    // defaults specify what attributes the model should
    // posses upon creation
    defaults: {
        text: 'hello world'
    }
});

var TodoModel = Backbone.Model.extend({
    defaults: {
        id: 1000,
        done: false,
        name: 'default task',
        deadline: new Date()
    }
});
Collection
Collections are ordered sets of models. It can be fetched from the server. Any
event that is triggered on a model in a collection will also be triggered on the
collection directly, for convenience.
 ● add()
 ● remove()

Comfortable backbone built data structure over models: array and stack.
 ● push()
 ● pop()
 ● unshift()
 ● shift()

Some handy methods:
 ● sort()
 ● where() - filters collection by given attribute
 ● fetch()
Collection
// Definitions
// Todo Model
var TodoModel = Backbone.Model.extend({
    defaults: {
        id: 1000,
        done: false,
        name: 'default task',
        deadline: new Date()
    }
});

// Todo Collection: ordered list of Todo models
var TodoCollection = Backbone.Collection.extend({
    model: TodoModel
});
View
The most disputable component in the Backbone framework.
Camp I:                 "It's NOT a controller"
Camp II:                "It's a controller"
Backbone Authors:       "If it helps any, in Backbone, the View class can also be
thought of as a kind of controller, dispatching events that originate from the UI,
with the HTML template serving as the true view."

What it does in life:
● renders the template and generates html
● handles user-generated events

Attributes and Methods partially of view and controller:
 ● tagName - html tag for the generated view
 ● $el - cached jQuery DOM selector
 ● events: {} - hash of event
 ● render() - rendering method
View
var GreetingView = Backbone.View.extend({
    // every view must have a specified render method
    // otherwise nothing would be seen
    render: function() {
        $('p').html(this.model.get('text'));
        return this;
    }
});

var greet = new GreetingModel();

new GreetingView({model: greet}).render()​




                                             Hello world Example
View
var RecordView = Backbone.View.extend({
    tagName: 'tr',
    events: {
        'click': 'performed'
    },
    initialize : function() {
        this.model.bind('change', this.render, this);
    },
    render: function() {
        var generatedHtml = _.template(this.template, {
            id: this.model.get('id'),
            done: this.model.get('done'),
            name: this.model.get('name'),
            deadline: this.model.get('deadline' )
        });
        $(this.el).html(generatedHtml );
        return this;
    },
    performed: function() {
        this.model.set('done', true);
    }
});
                                                          Todo Example
View
var RecordView = Backbone.View.extend( {
    tagName: 'tr',
    events: {
        'click': 'performed'
    },
    initialize: function() {
        this.model.bind('change', this.render, this);
    },
    render: function() {
        var generatedHtml = _.template(this.template, {
            id: this.model.get('id'),
            done: this.model.get('done'),
            name: this.model.get('name'),
            deadline: this.model.get('deadline')
        });
        $(this.el).html(generatedHtml);
        return this;
    },
    performed: function() {
        this.model.set('done', true);
    }
});
View
var RecordView = Backbone.View.extend( {
    tagName: 'tr',
    events: {
        'click': 'performed'
    },
    initialize: function() {
        this.model.bind('change', this.render, this);
    },
    render: function() {
        var generatedHtml = _.template(this.template, {
            id: this.model.get('id'),
            done: this.model.get('done'),
            name: this.model.get('name'),
            deadline: this.model.get('deadline')
        });
        $(this.el).html(generatedHtml);
        return this;
    },
    performed: function() {
        this.model.set('done', true);
    }
});
View
var RecordView = Backbone.View.extend( {
    tagName: 'tr',
    events: {
        'click': 'performed'
    },
    initialize: function() {
        this.model.bind('change', this.render, this);
    },
    render: function() {
        var generatedHtml = _.template(this.template, {
            id: this.model.get('id'),
            done: this.model.get('done'),
            name: this.model.get('name'),
            deadline: this.model.get('deadline')
        });
        $(this.el).html(generatedHtml);
        return this;
    },
    performed: function() {
        this.model.set('done', true);
    }
});
View
var RecordView = Backbone.View.extend( {
    tagName: 'tr',
    events: {
        'click': 'performed'
    },
    initialize : function() {
        this.model.bind('change', this.render, this);
    },
    render: function() {
        var generatedHtml = _.template(this.template, {
            id: this.model.get('id'),
            done: this.model.get('done'),
            name: this.model.get('name'),
            deadline: this.model.get('deadline')
        });
        $(this.el).html(generatedHtml);
        return this;
    },
    performed: function() {
        this.model.set('done', true);
    }
});
View
var RecordView = Backbone.View.extend( {
    tagName: 'tr',
    events: {
        'click': 'performed'
    },
    initialize: function() {
        this.model.bind('change', this.render, this);
    },
    render: function() {
        var generatedHtml = _.template(this.template, {
            id: this.model.get('id'),
            done: this.model.get('done'),
            name: this.model.get('name'),
            deadline: this.model.get('deadline' )
        });
        $(this.el).html(generatedHtml );
        return this;
    },
    performed: function() {
        this.model.set('done', true);
    }
});
Template
Underscore templating engine by default. It's possible to connect any other.
<tr>
    <td><%=   id %></td>
    <td><%=   done %></td>
    <td><%=   name %></td>
    <td><%=   deadline %></td>
</tr>​


●   Mixes template with the data from a model
●   Generates html
●   Append is with DOM element
render: function() {
        var generatedHtml = _.template(this.template, {
            id: this.model.get('id'),
            done: this.model.get('done'),
            name: this.model.get('name'),
            deadline: this.model.get('deadline')
        });
        $(this.el).html(generatedHtml);
        return this;
    },                                                         Todo Example
Event
Events is a module that can be mixed in to any object, giving the object the
ability to bind and trigger custom named events.


var object = {};

_.extend(object, Backbone.Events);

object.on("alert", function(msg) {
  alert("Triggered " + msg);
});

object.trigger("alert", "an event");​

                                                                 Event Example
Router & History
Backbone.Router provides methods for routing client-side pages, and
connecting them to actions and events.


window.Router = Backbone.Router.extend({
     routes: {
         '': 'tree',
         'folder/:name' : 'list'
     },
     initialize : function() {
         this.headerView = new HeaderView ();
         $('.header').html(this.headerView .render().el);
         ...
     },
     tree: function() {
         ...
     },
     list: function(name) {
         ...
     }
});​
Performance
●   All modern browsers support, IE 8+

●   Framework size: Backbone + Underscore = 89KB

●   Application size: 330KB
Conclusion
●   Lightweight

●   Great momentum: many project, community support

●   Good documentation

●   Binds to any JS library

More Related Content

What's hot

AngularJS: what is underneath the hood
AngularJS: what is underneath the hood AngularJS: what is underneath the hood
AngularJS: what is underneath the hood
DA-14
 
Writing Maintainable JavaScript
Writing Maintainable JavaScriptWriting Maintainable JavaScript
Writing Maintainable JavaScript
Andrew Dupont
 
Optimizing Angular Performance in Enterprise Single Page Apps
Optimizing Angular Performance in Enterprise Single Page AppsOptimizing Angular Performance in Enterprise Single Page Apps
Optimizing Angular Performance in Enterprise Single Page Apps
Morgan Stone
 
Data20161007
Data20161007Data20161007
Data20161007
capegmail
 
Client Side MVC & Angular
Client Side MVC & AngularClient Side MVC & Angular
Client Side MVC & Angular
Alexe Bogdan
 
Before there was Hoop Dreams, there was McDonald's: Strange and Beautiful
Before there was Hoop Dreams, there was McDonald's: Strange and BeautifulBefore there was Hoop Dreams, there was McDonald's: Strange and Beautiful
Before there was Hoop Dreams, there was McDonald's: Strange and Beautiful
chicagonewsonlineradio
 
Delivering a Responsive UI
Delivering a Responsive UIDelivering a Responsive UI
Delivering a Responsive UIRebecca Murphey
 
Beyond the DOM: Sane Structure for JS Apps
Beyond the DOM: Sane Structure for JS AppsBeyond the DOM: Sane Structure for JS Apps
Beyond the DOM: Sane Structure for JS Apps
Rebecca Murphey
 
AngulrJS Overview
AngulrJS OverviewAngulrJS Overview
AngulrJS Overview
Eyal Vardi
 
Decoupling with Design Patterns and Symfony2 DIC
Decoupling with Design Patterns and Symfony2 DICDecoupling with Design Patterns and Symfony2 DIC
Decoupling with Design Patterns and Symfony2 DIC
Konstantin Kudryashov
 
前端MVC 豆瓣说
前端MVC 豆瓣说前端MVC 豆瓣说
前端MVC 豆瓣说Ting Lv
 
Data binding w Androidzie
Data binding w AndroidzieData binding w Androidzie
Data binding w Androidzie
The Software House
 
Angular js is the future. maybe. @ ConFoo 2014 in Montreal (CA)
Angular js is the future. maybe. @ ConFoo 2014 in Montreal (CA)Angular js is the future. maybe. @ ConFoo 2014 in Montreal (CA)
Angular js is the future. maybe. @ ConFoo 2014 in Montreal (CA)
Alessandro Nadalin
 
Mad Max is back, plus the rest of our new reviews and notable screenings
Mad Max is back, plus the rest of our new reviews and notable screeningsMad Max is back, plus the rest of our new reviews and notable screenings
Mad Max is back, plus the rest of our new reviews and notable screenings
chicagonewsonlineradio
 
Databinding and Performance-Tuning in Angular 2
Databinding and Performance-Tuning in Angular 2Databinding and Performance-Tuning in Angular 2
Databinding and Performance-Tuning in Angular 2
Manfred Steyer
 
Tinkerbelles return home from their Guinness world-record attempt on Sunday
Tinkerbelles return home from their Guinness world-record attempt on SundayTinkerbelles return home from their Guinness world-record attempt on Sunday
Tinkerbelles return home from their Guinness world-record attempt on Sunday
chicagonewsyesterday
 
Cyclejs introduction
Cyclejs introductionCyclejs introduction
Cyclejs introduction
Arye Lukashevski
 
Why Sifu
Why SifuWhy Sifu
Why Sifu
LambdaWorks
 

What's hot (20)

AngularJS: what is underneath the hood
AngularJS: what is underneath the hood AngularJS: what is underneath the hood
AngularJS: what is underneath the hood
 
Writing Maintainable JavaScript
Writing Maintainable JavaScriptWriting Maintainable JavaScript
Writing Maintainable JavaScript
 
Optimizing Angular Performance in Enterprise Single Page Apps
Optimizing Angular Performance in Enterprise Single Page AppsOptimizing Angular Performance in Enterprise Single Page Apps
Optimizing Angular Performance in Enterprise Single Page Apps
 
Data20161007
Data20161007Data20161007
Data20161007
 
Client Side MVC & Angular
Client Side MVC & AngularClient Side MVC & Angular
Client Side MVC & Angular
 
Before there was Hoop Dreams, there was McDonald's: Strange and Beautiful
Before there was Hoop Dreams, there was McDonald's: Strange and BeautifulBefore there was Hoop Dreams, there was McDonald's: Strange and Beautiful
Before there was Hoop Dreams, there was McDonald's: Strange and Beautiful
 
Delivering a Responsive UI
Delivering a Responsive UIDelivering a Responsive UI
Delivering a Responsive UI
 
Beyond the DOM: Sane Structure for JS Apps
Beyond the DOM: Sane Structure for JS AppsBeyond the DOM: Sane Structure for JS Apps
Beyond the DOM: Sane Structure for JS Apps
 
AngulrJS Overview
AngulrJS OverviewAngulrJS Overview
AngulrJS Overview
 
Hidden rocks in Oracle ADF
Hidden rocks in Oracle ADFHidden rocks in Oracle ADF
Hidden rocks in Oracle ADF
 
Decoupling with Design Patterns and Symfony2 DIC
Decoupling with Design Patterns and Symfony2 DICDecoupling with Design Patterns and Symfony2 DIC
Decoupling with Design Patterns and Symfony2 DIC
 
前端MVC 豆瓣说
前端MVC 豆瓣说前端MVC 豆瓣说
前端MVC 豆瓣说
 
Data binding w Androidzie
Data binding w AndroidzieData binding w Androidzie
Data binding w Androidzie
 
Angular js is the future. maybe. @ ConFoo 2014 in Montreal (CA)
Angular js is the future. maybe. @ ConFoo 2014 in Montreal (CA)Angular js is the future. maybe. @ ConFoo 2014 in Montreal (CA)
Angular js is the future. maybe. @ ConFoo 2014 in Montreal (CA)
 
Mad Max is back, plus the rest of our new reviews and notable screenings
Mad Max is back, plus the rest of our new reviews and notable screeningsMad Max is back, plus the rest of our new reviews and notable screenings
Mad Max is back, plus the rest of our new reviews and notable screenings
 
Databinding and Performance-Tuning in Angular 2
Databinding and Performance-Tuning in Angular 2Databinding and Performance-Tuning in Angular 2
Databinding and Performance-Tuning in Angular 2
 
Tinkerbelles return home from their Guinness world-record attempt on Sunday
Tinkerbelles return home from their Guinness world-record attempt on SundayTinkerbelles return home from their Guinness world-record attempt on Sunday
Tinkerbelles return home from their Guinness world-record attempt on Sunday
 
BVJS
BVJSBVJS
BVJS
 
Cyclejs introduction
Cyclejs introductionCyclejs introduction
Cyclejs introduction
 
Why Sifu
Why SifuWhy Sifu
Why Sifu
 

Viewers also liked

Introduction To Backbone JS
Introduction To Backbone JSIntroduction To Backbone JS
Introduction To Backbone JS
paramisoft
 
Backbone.js
Backbone.jsBackbone.js
Backbone.jstonyskn
 
Structuring web applications with Backbone.js
Structuring web applications with Backbone.jsStructuring web applications with Backbone.js
Structuring web applications with Backbone.js
Diego Cardozo
 
Writing HTML5 Web Apps using Backbone.js and GAE
Writing HTML5 Web Apps using Backbone.js and GAEWriting HTML5 Web Apps using Backbone.js and GAE
Writing HTML5 Web Apps using Backbone.js and GAE
Ron Reiter
 
Introduction to Backbone - Workshop
Introduction to Backbone - WorkshopIntroduction to Backbone - Workshop
Introduction to Backbone - Workshop
Oren Farhi
 
Introduction to Backbone.js
Introduction to Backbone.jsIntroduction to Backbone.js
Introduction to Backbone.jsPragnesh Vaghela
 

Viewers also liked (7)

Introduction To Backbone JS
Introduction To Backbone JSIntroduction To Backbone JS
Introduction To Backbone JS
 
Backbone.js
Backbone.jsBackbone.js
Backbone.js
 
Backbone.js
Backbone.jsBackbone.js
Backbone.js
 
Structuring web applications with Backbone.js
Structuring web applications with Backbone.jsStructuring web applications with Backbone.js
Structuring web applications with Backbone.js
 
Writing HTML5 Web Apps using Backbone.js and GAE
Writing HTML5 Web Apps using Backbone.js and GAEWriting HTML5 Web Apps using Backbone.js and GAE
Writing HTML5 Web Apps using Backbone.js and GAE
 
Introduction to Backbone - Workshop
Introduction to Backbone - WorkshopIntroduction to Backbone - Workshop
Introduction to Backbone - Workshop
 
Introduction to Backbone.js
Introduction to Backbone.jsIntroduction to Backbone.js
Introduction to Backbone.js
 

Similar to Backbone Basics with Examples

Clean Javascript
Clean JavascriptClean Javascript
Clean Javascript
Ryunosuke SATO
 
Backbone js
Backbone jsBackbone js
Backbone js
Rohan Chandane
 
Backbone js
Backbone jsBackbone js
Backbone js
husnara mohammad
 
Viking academy backbone.js
Viking academy  backbone.jsViking academy  backbone.js
Viking academy backbone.js
Bert Wijnants
 
Understanding backbonejs
Understanding backbonejsUnderstanding backbonejs
Understanding backbonejs
Nick Lee
 
Backbone.js
Backbone.jsBackbone.js
Backbone.js
Omnia Helmi
 
Using Backbone.js with Drupal 7 and 8
Using Backbone.js with Drupal 7 and 8Using Backbone.js with Drupal 7 and 8
Using Backbone.js with Drupal 7 and 8Ovadiah Myrgorod
 
Patterns Are Good For Managers
Patterns Are Good For ManagersPatterns Are Good For Managers
Patterns Are Good For Managers
AgileThought
 
JSLab. Алексей Волков. "React на практике"
JSLab. Алексей Волков. "React на практике"JSLab. Алексей Волков. "React на практике"
JSLab. Алексей Волков. "React на практике"
GeeksLab Odessa
 
Backbone js
Backbone jsBackbone js
Backbone js
Knoldus Inc.
 
MVC on the Server and on the Client: How to Integrate Spring MVC and Backbone...
MVC on the Server and on the Client: How to Integrate Spring MVC and Backbone...MVC on the Server and on the Client: How to Integrate Spring MVC and Backbone...
MVC on the Server and on the Client: How to Integrate Spring MVC and Backbone...
jaxconf
 
Introduction to Spring MVC
Introduction to Spring MVCIntroduction to Spring MVC
Introduction to Spring MVC
Richard Paul
 
Javascript Frameworks for Joomla
Javascript Frameworks for JoomlaJavascript Frameworks for Joomla
Javascript Frameworks for JoomlaLuke Summerfield
 
JavaScript Refactoring
JavaScript RefactoringJavaScript Refactoring
JavaScript Refactoring
Krzysztof Szafranek
 
Django Class-based views (Slovenian)
Django Class-based views (Slovenian)Django Class-based views (Slovenian)
Django Class-based views (Slovenian)Luka Zakrajšek
 
MVC on the server and on the client
MVC on the server and on the clientMVC on the server and on the client
MVC on the server and on the client
Sebastiano Armeli
 
Javascript first-class citizenery
Javascript first-class citizeneryJavascript first-class citizenery
Javascript first-class citizenery
toddbr
 
Taming that client side mess with Backbone.js
Taming that client side mess with Backbone.jsTaming that client side mess with Backbone.js
Taming that client side mess with Backbone.jsJarod Ferguson
 

Similar to Backbone Basics with Examples (20)

Clean Javascript
Clean JavascriptClean Javascript
Clean Javascript
 
Backbone js
Backbone jsBackbone js
Backbone js
 
Backbone js
Backbone jsBackbone js
Backbone js
 
Viking academy backbone.js
Viking academy  backbone.jsViking academy  backbone.js
Viking academy backbone.js
 
Understanding backbonejs
Understanding backbonejsUnderstanding backbonejs
Understanding backbonejs
 
Backbone.js
Backbone.jsBackbone.js
Backbone.js
 
Using Backbone.js with Drupal 7 and 8
Using Backbone.js with Drupal 7 and 8Using Backbone.js with Drupal 7 and 8
Using Backbone.js with Drupal 7 and 8
 
Backbone js-slides
Backbone js-slidesBackbone js-slides
Backbone js-slides
 
Patterns Are Good For Managers
Patterns Are Good For ManagersPatterns Are Good For Managers
Patterns Are Good For Managers
 
JSLab. Алексей Волков. "React на практике"
JSLab. Алексей Волков. "React на практике"JSLab. Алексей Волков. "React на практике"
JSLab. Алексей Волков. "React на практике"
 
Backbone js
Backbone jsBackbone js
Backbone js
 
MVC on the Server and on the Client: How to Integrate Spring MVC and Backbone...
MVC on the Server and on the Client: How to Integrate Spring MVC and Backbone...MVC on the Server and on the Client: How to Integrate Spring MVC and Backbone...
MVC on the Server and on the Client: How to Integrate Spring MVC and Backbone...
 
Introduction to Spring MVC
Introduction to Spring MVCIntroduction to Spring MVC
Introduction to Spring MVC
 
Javascript Frameworks for Joomla
Javascript Frameworks for JoomlaJavascript Frameworks for Joomla
Javascript Frameworks for Joomla
 
JavaScript Refactoring
JavaScript RefactoringJavaScript Refactoring
JavaScript Refactoring
 
Django Class-based views (Slovenian)
Django Class-based views (Slovenian)Django Class-based views (Slovenian)
Django Class-based views (Slovenian)
 
Introduction to angular js
Introduction to angular jsIntroduction to angular js
Introduction to angular js
 
MVC on the server and on the client
MVC on the server and on the clientMVC on the server and on the client
MVC on the server and on the client
 
Javascript first-class citizenery
Javascript first-class citizeneryJavascript first-class citizenery
Javascript first-class citizenery
 
Taming that client side mess with Backbone.js
Taming that client side mess with Backbone.jsTaming that client side mess with Backbone.js
Taming that client side mess with Backbone.js
 

More from Sergey Bolshchikov

Onboarding for Software Engineers Done Right
Onboarding for Software Engineers Done RightOnboarding for Software Engineers Done Right
Onboarding for Software Engineers Done Right
Sergey Bolshchikov
 
Pragmatic React Workshop
Pragmatic React WorkshopPragmatic React Workshop
Pragmatic React Workshop
Sergey Bolshchikov
 
Microservices on the client side
Microservices on the client sideMicroservices on the client side
Microservices on the client side
Sergey Bolshchikov
 
ES2015 Quiz
ES2015 QuizES2015 Quiz
ES2015 Quiz
Sergey Bolshchikov
 
Talking code: How To
Talking code: How ToTalking code: How To
Talking code: How To
Sergey Bolshchikov
 
Values & Culture of Continuous Deliver
Values & Culture of Continuous DeliverValues & Culture of Continuous Deliver
Values & Culture of Continuous Deliver
Sergey Bolshchikov
 
Protractor: Tips & Tricks
Protractor: Tips & TricksProtractor: Tips & Tricks
Protractor: Tips & Tricks
Sergey Bolshchikov
 
Continuous Delivery for Front-End Engineers
Continuous Delivery for Front-End EngineersContinuous Delivery for Front-End Engineers
Continuous Delivery for Front-End Engineers
Sergey Bolshchikov
 
Зачем нужен EmberJS, если мне хвататет jQuery
Зачем нужен EmberJS, если мне хвататет jQueryЗачем нужен EmberJS, если мне хвататет jQuery
Зачем нужен EmberJS, если мне хвататет jQuery
Sergey Bolshchikov
 
Ember Reusable Components and Widgets
Ember Reusable Components and WidgetsEmber Reusable Components and Widgets
Ember Reusable Components and Widgets
Sergey Bolshchikov
 
Front End Development: The Important Parts
Front End Development: The Important PartsFront End Development: The Important Parts
Front End Development: The Important Parts
Sergey Bolshchikov
 
Web Projects: From Theory To Practice
Web Projects: From Theory To PracticeWeb Projects: From Theory To Practice
Web Projects: From Theory To Practice
Sergey Bolshchikov
 
AngularJS Basics with Example
AngularJS Basics with ExampleAngularJS Basics with Example
AngularJS Basics with Example
Sergey Bolshchikov
 
JS Single-Page Web App Essentials
JS Single-Page Web App EssentialsJS Single-Page Web App Essentials
JS Single-Page Web App Essentials
Sergey Bolshchikov
 

More from Sergey Bolshchikov (14)

Onboarding for Software Engineers Done Right
Onboarding for Software Engineers Done RightOnboarding for Software Engineers Done Right
Onboarding for Software Engineers Done Right
 
Pragmatic React Workshop
Pragmatic React WorkshopPragmatic React Workshop
Pragmatic React Workshop
 
Microservices on the client side
Microservices on the client sideMicroservices on the client side
Microservices on the client side
 
ES2015 Quiz
ES2015 QuizES2015 Quiz
ES2015 Quiz
 
Talking code: How To
Talking code: How ToTalking code: How To
Talking code: How To
 
Values & Culture of Continuous Deliver
Values & Culture of Continuous DeliverValues & Culture of Continuous Deliver
Values & Culture of Continuous Deliver
 
Protractor: Tips & Tricks
Protractor: Tips & TricksProtractor: Tips & Tricks
Protractor: Tips & Tricks
 
Continuous Delivery for Front-End Engineers
Continuous Delivery for Front-End EngineersContinuous Delivery for Front-End Engineers
Continuous Delivery for Front-End Engineers
 
Зачем нужен EmberJS, если мне хвататет jQuery
Зачем нужен EmberJS, если мне хвататет jQueryЗачем нужен EmberJS, если мне хвататет jQuery
Зачем нужен EmberJS, если мне хвататет jQuery
 
Ember Reusable Components and Widgets
Ember Reusable Components and WidgetsEmber Reusable Components and Widgets
Ember Reusable Components and Widgets
 
Front End Development: The Important Parts
Front End Development: The Important PartsFront End Development: The Important Parts
Front End Development: The Important Parts
 
Web Projects: From Theory To Practice
Web Projects: From Theory To PracticeWeb Projects: From Theory To Practice
Web Projects: From Theory To Practice
 
AngularJS Basics with Example
AngularJS Basics with ExampleAngularJS Basics with Example
AngularJS Basics with Example
 
JS Single-Page Web App Essentials
JS Single-Page Web App EssentialsJS Single-Page Web App Essentials
JS Single-Page Web App Essentials
 

Recently uploaded

falcon-invoice-discounting-a-premier-platform-for-investors-in-india
falcon-invoice-discounting-a-premier-platform-for-investors-in-indiafalcon-invoice-discounting-a-premier-platform-for-investors-in-india
falcon-invoice-discounting-a-premier-platform-for-investors-in-india
Falcon Invoice Discounting
 
Skye Residences | Extended Stay Residences Near Toronto Airport
Skye Residences | Extended Stay Residences Near Toronto AirportSkye Residences | Extended Stay Residences Near Toronto Airport
Skye Residences | Extended Stay Residences Near Toronto Airport
marketingjdass
 
3.0 Project 2_ Developing My Brand Identity Kit.pptx
3.0 Project 2_ Developing My Brand Identity Kit.pptx3.0 Project 2_ Developing My Brand Identity Kit.pptx
3.0 Project 2_ Developing My Brand Identity Kit.pptx
tanyjahb
 
Introduction to Amazon company 111111111111
Introduction to Amazon company 111111111111Introduction to Amazon company 111111111111
Introduction to Amazon company 111111111111
zoyaansari11365
 
5 Things You Need To Know Before Hiring a Videographer
5 Things You Need To Know Before Hiring a Videographer5 Things You Need To Know Before Hiring a Videographer
5 Things You Need To Know Before Hiring a Videographer
ofm712785
 
Attending a job Interview for B1 and B2 Englsih learners
Attending a job Interview for B1 and B2 Englsih learnersAttending a job Interview for B1 and B2 Englsih learners
Attending a job Interview for B1 and B2 Englsih learners
Erika906060
 
Role of Remote Sensing and Monitoring in Mining
Role of Remote Sensing and Monitoring in MiningRole of Remote Sensing and Monitoring in Mining
Role of Remote Sensing and Monitoring in Mining
Naaraayani Minerals Pvt.Ltd
 
Enterprise Excellence is Inclusive Excellence.pdf
Enterprise Excellence is Inclusive Excellence.pdfEnterprise Excellence is Inclusive Excellence.pdf
Enterprise Excellence is Inclusive Excellence.pdf
KaiNexus
 
Digital Transformation in PLM - WHAT and HOW - for distribution.pdf
Digital Transformation in PLM - WHAT and HOW - for distribution.pdfDigital Transformation in PLM - WHAT and HOW - for distribution.pdf
Digital Transformation in PLM - WHAT and HOW - for distribution.pdf
Jos Voskuil
 
Exploring Patterns of Connection with Social Dreaming
Exploring Patterns of Connection with Social DreamingExploring Patterns of Connection with Social Dreaming
Exploring Patterns of Connection with Social Dreaming
Nicola Wreford-Howard
 
BeMetals Presentation_May_22_2024 .pdf
BeMetals Presentation_May_22_2024   .pdfBeMetals Presentation_May_22_2024   .pdf
BeMetals Presentation_May_22_2024 .pdf
DerekIwanaka1
 
Project File Report BBA 6th semester.pdf
Project File Report BBA 6th semester.pdfProject File Report BBA 6th semester.pdf
Project File Report BBA 6th semester.pdf
RajPriye
 
The-McKinsey-7S-Framework. strategic management
The-McKinsey-7S-Framework. strategic managementThe-McKinsey-7S-Framework. strategic management
The-McKinsey-7S-Framework. strategic management
Bojamma2
 
Memorandum Of Association Constitution of Company.ppt
Memorandum Of Association Constitution of Company.pptMemorandum Of Association Constitution of Company.ppt
Memorandum Of Association Constitution of Company.ppt
seri bangash
 
What are the main advantages of using HR recruiter services.pdf
What are the main advantages of using HR recruiter services.pdfWhat are the main advantages of using HR recruiter services.pdf
What are the main advantages of using HR recruiter services.pdf
HumanResourceDimensi1
 
Maksym Vyshnivetskyi: PMO Quality Management (UA)
Maksym Vyshnivetskyi: PMO Quality Management (UA)Maksym Vyshnivetskyi: PMO Quality Management (UA)
Maksym Vyshnivetskyi: PMO Quality Management (UA)
Lviv Startup Club
 
Premium MEAN Stack Development Solutions for Modern Businesses
Premium MEAN Stack Development Solutions for Modern BusinessesPremium MEAN Stack Development Solutions for Modern Businesses
Premium MEAN Stack Development Solutions for Modern Businesses
SynapseIndia
 
Brand Analysis for an artist named Struan
Brand Analysis for an artist named StruanBrand Analysis for an artist named Struan
Brand Analysis for an artist named Struan
sarahvanessa51503
 
Taurus Zodiac Sign_ Personality Traits and Sign Dates.pptx
Taurus Zodiac Sign_ Personality Traits and Sign Dates.pptxTaurus Zodiac Sign_ Personality Traits and Sign Dates.pptx
Taurus Zodiac Sign_ Personality Traits and Sign Dates.pptx
my Pandit
 
Search Disrupted Google’s Leaked Documents Rock the SEO World.pdf
Search Disrupted Google’s Leaked Documents Rock the SEO World.pdfSearch Disrupted Google’s Leaked Documents Rock the SEO World.pdf
Search Disrupted Google’s Leaked Documents Rock the SEO World.pdf
Arihant Webtech Pvt. Ltd
 

Recently uploaded (20)

falcon-invoice-discounting-a-premier-platform-for-investors-in-india
falcon-invoice-discounting-a-premier-platform-for-investors-in-indiafalcon-invoice-discounting-a-premier-platform-for-investors-in-india
falcon-invoice-discounting-a-premier-platform-for-investors-in-india
 
Skye Residences | Extended Stay Residences Near Toronto Airport
Skye Residences | Extended Stay Residences Near Toronto AirportSkye Residences | Extended Stay Residences Near Toronto Airport
Skye Residences | Extended Stay Residences Near Toronto Airport
 
3.0 Project 2_ Developing My Brand Identity Kit.pptx
3.0 Project 2_ Developing My Brand Identity Kit.pptx3.0 Project 2_ Developing My Brand Identity Kit.pptx
3.0 Project 2_ Developing My Brand Identity Kit.pptx
 
Introduction to Amazon company 111111111111
Introduction to Amazon company 111111111111Introduction to Amazon company 111111111111
Introduction to Amazon company 111111111111
 
5 Things You Need To Know Before Hiring a Videographer
5 Things You Need To Know Before Hiring a Videographer5 Things You Need To Know Before Hiring a Videographer
5 Things You Need To Know Before Hiring a Videographer
 
Attending a job Interview for B1 and B2 Englsih learners
Attending a job Interview for B1 and B2 Englsih learnersAttending a job Interview for B1 and B2 Englsih learners
Attending a job Interview for B1 and B2 Englsih learners
 
Role of Remote Sensing and Monitoring in Mining
Role of Remote Sensing and Monitoring in MiningRole of Remote Sensing and Monitoring in Mining
Role of Remote Sensing and Monitoring in Mining
 
Enterprise Excellence is Inclusive Excellence.pdf
Enterprise Excellence is Inclusive Excellence.pdfEnterprise Excellence is Inclusive Excellence.pdf
Enterprise Excellence is Inclusive Excellence.pdf
 
Digital Transformation in PLM - WHAT and HOW - for distribution.pdf
Digital Transformation in PLM - WHAT and HOW - for distribution.pdfDigital Transformation in PLM - WHAT and HOW - for distribution.pdf
Digital Transformation in PLM - WHAT and HOW - for distribution.pdf
 
Exploring Patterns of Connection with Social Dreaming
Exploring Patterns of Connection with Social DreamingExploring Patterns of Connection with Social Dreaming
Exploring Patterns of Connection with Social Dreaming
 
BeMetals Presentation_May_22_2024 .pdf
BeMetals Presentation_May_22_2024   .pdfBeMetals Presentation_May_22_2024   .pdf
BeMetals Presentation_May_22_2024 .pdf
 
Project File Report BBA 6th semester.pdf
Project File Report BBA 6th semester.pdfProject File Report BBA 6th semester.pdf
Project File Report BBA 6th semester.pdf
 
The-McKinsey-7S-Framework. strategic management
The-McKinsey-7S-Framework. strategic managementThe-McKinsey-7S-Framework. strategic management
The-McKinsey-7S-Framework. strategic management
 
Memorandum Of Association Constitution of Company.ppt
Memorandum Of Association Constitution of Company.pptMemorandum Of Association Constitution of Company.ppt
Memorandum Of Association Constitution of Company.ppt
 
What are the main advantages of using HR recruiter services.pdf
What are the main advantages of using HR recruiter services.pdfWhat are the main advantages of using HR recruiter services.pdf
What are the main advantages of using HR recruiter services.pdf
 
Maksym Vyshnivetskyi: PMO Quality Management (UA)
Maksym Vyshnivetskyi: PMO Quality Management (UA)Maksym Vyshnivetskyi: PMO Quality Management (UA)
Maksym Vyshnivetskyi: PMO Quality Management (UA)
 
Premium MEAN Stack Development Solutions for Modern Businesses
Premium MEAN Stack Development Solutions for Modern BusinessesPremium MEAN Stack Development Solutions for Modern Businesses
Premium MEAN Stack Development Solutions for Modern Businesses
 
Brand Analysis for an artist named Struan
Brand Analysis for an artist named StruanBrand Analysis for an artist named Struan
Brand Analysis for an artist named Struan
 
Taurus Zodiac Sign_ Personality Traits and Sign Dates.pptx
Taurus Zodiac Sign_ Personality Traits and Sign Dates.pptxTaurus Zodiac Sign_ Personality Traits and Sign Dates.pptx
Taurus Zodiac Sign_ Personality Traits and Sign Dates.pptx
 
Search Disrupted Google’s Leaked Documents Rock the SEO World.pdf
Search Disrupted Google’s Leaked Documents Rock the SEO World.pdfSearch Disrupted Google’s Leaked Documents Rock the SEO World.pdf
Search Disrupted Google’s Leaked Documents Rock the SEO World.pdf
 

Backbone Basics with Examples

  • 1. 03 Backbone Framework Analysis Public Code Repository by Sergey N. Bolshchikov http://bolshchikov.net sergey.bolshchikov@new-proimage.com New ProImage, 2012
  • 2. Outline I. Introduction II. Dependencies III. Components a. Model b. Collection c. View IV. Utilities a. Router b. History V. Conclusion
  • 3. Shortly: 5 things Backbone.js gives structure to web applications by providing models with key-value binding and custom events, collections with a rich API of enumerable functions, views with declarative event handling, and connects it all to your existing API over a RESTful JSON interface.
  • 4. Shortly: 1 Backbone.js gives structure to web applications by providing models with key-value binding and custom events, collections with a rich API of enumerable functions, views with declarative event handling, and connects it all to your existing API over a RESTful JSON interface.
  • 5. Shortly: 2 Backbone.js gives structure to web applications by providing models with key-value binding and custom events, collections with a rich API of enumerable functions, views with declarative event handling, and connects it all to your existing API over a RESTful JSON interface.
  • 6. Shortly: 3 Backbone.js gives structure to web applications by providing models with key-value binding and custom events, collections with a rich API of enumerable functions, views with declarative event handling, and connects it all to your existing API over a RESTful JSON interface.
  • 7. Shortly: 4 Backbone.js gives structure to web applications by providing models with key-value binding and custom events, collections with a rich API of enumerable functions, views with declarative event handling, and connects it all to your existing API over a RESTful JSON interface.
  • 8. Shortly: 5 Backbone.js gives structure to web applications by providing models with key-value binding and custom events, collections with a rich API of enumerable functions,views with declarative event handling, and connects it all to your existing API over a RESTful JSON interface.
  • 9. Dependencies Backbone Underscore json2.js [jQuery]
  • 11. Model Backbone model contains interactive data. It possess different useful properties and methods: ● id - modelID ● idAttribute - databaseID ● get(attrName) - returns attribute value ● set(attrName, attrValue) - sets the value for the named attribute ● clear() - removes all model attributes ● toJSON() - return a copy of the model's attributes for JSON stringification ● url - relative URL where the model's resource would be located on the server ● fetch() - gets the latest version of the model from the server ● save() - saves the model to the DB ● validate() - checks the given data before set() and save() P.S. Almost never is predefined
  • 12. Model var GreetingModel = Backbone.Model.extend({ // defaults specify what attributes the model should // posses upon creation defaults: { text: 'hello world' } }); var TodoModel = Backbone.Model.extend({ defaults: { id: 1000, done: false, name: 'default task', deadline: new Date() } });
  • 13. Collection Collections are ordered sets of models. It can be fetched from the server. Any event that is triggered on a model in a collection will also be triggered on the collection directly, for convenience. ● add() ● remove() Comfortable backbone built data structure over models: array and stack. ● push() ● pop() ● unshift() ● shift() Some handy methods: ● sort() ● where() - filters collection by given attribute ● fetch()
  • 14. Collection // Definitions // Todo Model var TodoModel = Backbone.Model.extend({ defaults: { id: 1000, done: false, name: 'default task', deadline: new Date() } }); // Todo Collection: ordered list of Todo models var TodoCollection = Backbone.Collection.extend({ model: TodoModel });
  • 15. View The most disputable component in the Backbone framework. Camp I: "It's NOT a controller" Camp II: "It's a controller" Backbone Authors: "If it helps any, in Backbone, the View class can also be thought of as a kind of controller, dispatching events that originate from the UI, with the HTML template serving as the true view." What it does in life: ● renders the template and generates html ● handles user-generated events Attributes and Methods partially of view and controller: ● tagName - html tag for the generated view ● $el - cached jQuery DOM selector ● events: {} - hash of event ● render() - rendering method
  • 16. View var GreetingView = Backbone.View.extend({ // every view must have a specified render method // otherwise nothing would be seen render: function() { $('p').html(this.model.get('text')); return this; } }); var greet = new GreetingModel(); new GreetingView({model: greet}).render()​ Hello world Example
  • 17. View var RecordView = Backbone.View.extend({ tagName: 'tr', events: { 'click': 'performed' }, initialize : function() { this.model.bind('change', this.render, this); }, render: function() { var generatedHtml = _.template(this.template, { id: this.model.get('id'), done: this.model.get('done'), name: this.model.get('name'), deadline: this.model.get('deadline' ) }); $(this.el).html(generatedHtml ); return this; }, performed: function() { this.model.set('done', true); } }); Todo Example
  • 18. View var RecordView = Backbone.View.extend( { tagName: 'tr', events: { 'click': 'performed' }, initialize: function() { this.model.bind('change', this.render, this); }, render: function() { var generatedHtml = _.template(this.template, { id: this.model.get('id'), done: this.model.get('done'), name: this.model.get('name'), deadline: this.model.get('deadline') }); $(this.el).html(generatedHtml); return this; }, performed: function() { this.model.set('done', true); } });
  • 19. View var RecordView = Backbone.View.extend( { tagName: 'tr', events: { 'click': 'performed' }, initialize: function() { this.model.bind('change', this.render, this); }, render: function() { var generatedHtml = _.template(this.template, { id: this.model.get('id'), done: this.model.get('done'), name: this.model.get('name'), deadline: this.model.get('deadline') }); $(this.el).html(generatedHtml); return this; }, performed: function() { this.model.set('done', true); } });
  • 20. View var RecordView = Backbone.View.extend( { tagName: 'tr', events: { 'click': 'performed' }, initialize: function() { this.model.bind('change', this.render, this); }, render: function() { var generatedHtml = _.template(this.template, { id: this.model.get('id'), done: this.model.get('done'), name: this.model.get('name'), deadline: this.model.get('deadline') }); $(this.el).html(generatedHtml); return this; }, performed: function() { this.model.set('done', true); } });
  • 21. View var RecordView = Backbone.View.extend( { tagName: 'tr', events: { 'click': 'performed' }, initialize : function() { this.model.bind('change', this.render, this); }, render: function() { var generatedHtml = _.template(this.template, { id: this.model.get('id'), done: this.model.get('done'), name: this.model.get('name'), deadline: this.model.get('deadline') }); $(this.el).html(generatedHtml); return this; }, performed: function() { this.model.set('done', true); } });
  • 22. View var RecordView = Backbone.View.extend( { tagName: 'tr', events: { 'click': 'performed' }, initialize: function() { this.model.bind('change', this.render, this); }, render: function() { var generatedHtml = _.template(this.template, { id: this.model.get('id'), done: this.model.get('done'), name: this.model.get('name'), deadline: this.model.get('deadline' ) }); $(this.el).html(generatedHtml ); return this; }, performed: function() { this.model.set('done', true); } });
  • 23. Template Underscore templating engine by default. It's possible to connect any other. <tr> <td><%= id %></td> <td><%= done %></td> <td><%= name %></td> <td><%= deadline %></td> </tr>​ ● Mixes template with the data from a model ● Generates html ● Append is with DOM element render: function() { var generatedHtml = _.template(this.template, { id: this.model.get('id'), done: this.model.get('done'), name: this.model.get('name'), deadline: this.model.get('deadline') }); $(this.el).html(generatedHtml); return this; }, Todo Example
  • 24. Event Events is a module that can be mixed in to any object, giving the object the ability to bind and trigger custom named events. var object = {}; _.extend(object, Backbone.Events); object.on("alert", function(msg) { alert("Triggered " + msg); }); object.trigger("alert", "an event");​ Event Example
  • 25. Router & History Backbone.Router provides methods for routing client-side pages, and connecting them to actions and events. window.Router = Backbone.Router.extend({ routes: { '': 'tree', 'folder/:name' : 'list' }, initialize : function() { this.headerView = new HeaderView (); $('.header').html(this.headerView .render().el); ... }, tree: function() { ... }, list: function(name) { ... } });​
  • 26. Performance ● All modern browsers support, IE 8+ ● Framework size: Backbone + Underscore = 89KB ● Application size: 330KB
  • 27. Conclusion ● Lightweight ● Great momentum: many project, community support ● Good documentation ● Binds to any JS library