SlideShare ist ein Scribd-Unternehmen logo
1 von 27
Downloaden Sie, um offline zu lesen
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

Weitere ähnliche Inhalte

Was ist angesagt?

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 JavaScriptAndrew 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 AppsMorgan Stone
 
Data20161007
Data20161007Data20161007
Data20161007capegmail
 
Client Side MVC & Angular
Client Side MVC & AngularClient Side MVC & Angular
Client Side MVC & AngularAlexe 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 Beautifulchicagonewsonlineradio
 
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 AppsRebecca Murphey
 
AngulrJS Overview
AngulrJS OverviewAngulrJS Overview
AngulrJS OverviewEyal 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 DICKonstantin Kudryashov
 
前端MVC 豆瓣说
前端MVC 豆瓣说前端MVC 豆瓣说
前端MVC 豆瓣说Ting Lv
 
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 screeningschicagonewsonlineradio
 
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 2Manfred 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 Sundaychicagonewsyesterday
 

Was ist angesagt? (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
 

Andere mochten auch

Introduction To Backbone JS
Introduction To Backbone JSIntroduction To Backbone JS
Introduction To Backbone JSparamisoft
 
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.jsDiego 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 GAERon Reiter
 
Introduction to Backbone - Workshop
Introduction to Backbone - WorkshopIntroduction to Backbone - Workshop
Introduction to Backbone - WorkshopOren Farhi
 
Introduction to Backbone.js
Introduction to Backbone.jsIntroduction to Backbone.js
Introduction to Backbone.jsPragnesh Vaghela
 

Andere mochten auch (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
 

Ähnlich wie Backbone Basics with Examples

Viking academy backbone.js
Viking academy  backbone.jsViking academy  backbone.js
Viking academy backbone.jsBert Wijnants
 
Understanding backbonejs
Understanding backbonejsUnderstanding backbonejs
Understanding backbonejsNick Lee
 
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 ManagersAgileThought
 
JSLab. Алексей Волков. "React на практике"
JSLab. Алексей Волков. "React на практике"JSLab. Алексей Волков. "React на практике"
JSLab. Алексей Волков. "React на практике"GeeksLab Odessa
 
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 MVCRichard Paul
 
Javascript Frameworks for Joomla
Javascript Frameworks for JoomlaJavascript Frameworks for Joomla
Javascript Frameworks for JoomlaLuke Summerfield
 
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 clientSebastiano Armeli
 
Javascript first-class citizenery
Javascript first-class citizeneryJavascript first-class citizenery
Javascript first-class citizenerytoddbr
 
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
 

Ähnlich wie 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
 

Mehr von Sergey Bolshchikov

Onboarding for Software Engineers Done Right
Onboarding for Software Engineers Done RightOnboarding for Software Engineers Done Right
Onboarding for Software Engineers Done RightSergey Bolshchikov
 
Microservices on the client side
Microservices on the client sideMicroservices on the client side
Microservices on the client sideSergey Bolshchikov
 
Values & Culture of Continuous Deliver
Values & Culture of Continuous DeliverValues & Culture of Continuous Deliver
Values & Culture of Continuous DeliverSergey Bolshchikov
 
Continuous Delivery for Front-End Engineers
Continuous Delivery for Front-End EngineersContinuous Delivery for Front-End Engineers
Continuous Delivery for Front-End EngineersSergey Bolshchikov
 
Зачем нужен EmberJS, если мне хвататет jQuery
Зачем нужен EmberJS, если мне хвататет jQueryЗачем нужен EmberJS, если мне хвататет jQuery
Зачем нужен EmberJS, если мне хвататет jQuerySergey Bolshchikov
 
Ember Reusable Components and Widgets
Ember Reusable Components and WidgetsEmber Reusable Components and Widgets
Ember Reusable Components and WidgetsSergey Bolshchikov
 
Front End Development: The Important Parts
Front End Development: The Important PartsFront End Development: The Important Parts
Front End Development: The Important PartsSergey Bolshchikov
 
Web Projects: From Theory To Practice
Web Projects: From Theory To PracticeWeb Projects: From Theory To Practice
Web Projects: From Theory To PracticeSergey Bolshchikov
 
JS Single-Page Web App Essentials
JS Single-Page Web App EssentialsJS Single-Page Web App Essentials
JS Single-Page Web App EssentialsSergey Bolshchikov
 

Mehr von 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
 

Kürzlich hochgeladen

Falcon's Invoice Discounting: Your Path to Prosperity
Falcon's Invoice Discounting: Your Path to ProsperityFalcon's Invoice Discounting: Your Path to Prosperity
Falcon's Invoice Discounting: Your Path to Prosperityhemanthkumar470700
 
Mondelez State of Snacking and Future Trends 2023
Mondelez State of Snacking and Future Trends 2023Mondelez State of Snacking and Future Trends 2023
Mondelez State of Snacking and Future Trends 2023Neil Kimberley
 
Mysore Call Girls 8617370543 WhatsApp Number 24x7 Best Services
Mysore Call Girls 8617370543 WhatsApp Number 24x7 Best ServicesMysore Call Girls 8617370543 WhatsApp Number 24x7 Best Services
Mysore Call Girls 8617370543 WhatsApp Number 24x7 Best ServicesDipal Arora
 
The Path to Product Excellence: Avoiding Common Pitfalls and Enhancing Commun...
The Path to Product Excellence: Avoiding Common Pitfalls and Enhancing Commun...The Path to Product Excellence: Avoiding Common Pitfalls and Enhancing Commun...
The Path to Product Excellence: Avoiding Common Pitfalls and Enhancing Commun...Aggregage
 
Call Girls Electronic City Just Call 👗 7737669865 👗 Top Class Call Girl Servi...
Call Girls Electronic City Just Call 👗 7737669865 👗 Top Class Call Girl Servi...Call Girls Electronic City Just Call 👗 7737669865 👗 Top Class Call Girl Servi...
Call Girls Electronic City Just Call 👗 7737669865 👗 Top Class Call Girl Servi...amitlee9823
 
B.COM Unit – 4 ( CORPORATE SOCIAL RESPONSIBILITY ( CSR ).pptx
B.COM Unit – 4 ( CORPORATE SOCIAL RESPONSIBILITY ( CSR ).pptxB.COM Unit – 4 ( CORPORATE SOCIAL RESPONSIBILITY ( CSR ).pptx
B.COM Unit – 4 ( CORPORATE SOCIAL RESPONSIBILITY ( CSR ).pptxpriyanshujha201
 
BAGALUR CALL GIRL IN 98274*61493 ❤CALL GIRLS IN ESCORT SERVICE❤CALL GIRL
BAGALUR CALL GIRL IN 98274*61493 ❤CALL GIRLS IN ESCORT SERVICE❤CALL GIRLBAGALUR CALL GIRL IN 98274*61493 ❤CALL GIRLS IN ESCORT SERVICE❤CALL GIRL
BAGALUR CALL GIRL IN 98274*61493 ❤CALL GIRLS IN ESCORT SERVICE❤CALL GIRLkapoorjyoti4444
 
Call Girls Pune Just Call 9907093804 Top Class Call Girl Service Available
Call Girls Pune Just Call 9907093804 Top Class Call Girl Service AvailableCall Girls Pune Just Call 9907093804 Top Class Call Girl Service Available
Call Girls Pune Just Call 9907093804 Top Class Call Girl Service AvailableDipal Arora
 
FULL ENJOY Call Girls In Majnu Ka Tilla, Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Majnu Ka Tilla, Delhi Contact Us 8377877756FULL ENJOY Call Girls In Majnu Ka Tilla, Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Majnu Ka Tilla, Delhi Contact Us 8377877756dollysharma2066
 
Call Girls In Panjim North Goa 9971646499 Genuine Service
Call Girls In Panjim North Goa 9971646499 Genuine ServiceCall Girls In Panjim North Goa 9971646499 Genuine Service
Call Girls In Panjim North Goa 9971646499 Genuine Serviceritikaroy0888
 
A DAY IN THE LIFE OF A SALESMAN / WOMAN
A DAY IN THE LIFE OF A  SALESMAN / WOMANA DAY IN THE LIFE OF A  SALESMAN / WOMAN
A DAY IN THE LIFE OF A SALESMAN / WOMANIlamathiKannappan
 
Monthly Social Media Update April 2024 pptx.pptx
Monthly Social Media Update April 2024 pptx.pptxMonthly Social Media Update April 2024 pptx.pptx
Monthly Social Media Update April 2024 pptx.pptxAndy Lambert
 
John Halpern sued for sexual assault.pdf
John Halpern sued for sexual assault.pdfJohn Halpern sued for sexual assault.pdf
John Halpern sued for sexual assault.pdfAmzadHosen3
 
Call Girls Navi Mumbai Just Call 9907093804 Top Class Call Girl Service Avail...
Call Girls Navi Mumbai Just Call 9907093804 Top Class Call Girl Service Avail...Call Girls Navi Mumbai Just Call 9907093804 Top Class Call Girl Service Avail...
Call Girls Navi Mumbai Just Call 9907093804 Top Class Call Girl Service Avail...Dipal Arora
 
Call Girls Jp Nagar Just Call 👗 7737669865 👗 Top Class Call Girl Service Bang...
Call Girls Jp Nagar Just Call 👗 7737669865 👗 Top Class Call Girl Service Bang...Call Girls Jp Nagar Just Call 👗 7737669865 👗 Top Class Call Girl Service Bang...
Call Girls Jp Nagar Just Call 👗 7737669865 👗 Top Class Call Girl Service Bang...amitlee9823
 
Enhancing and Restoring Safety & Quality Cultures - Dave Litwiller - May 2024...
Enhancing and Restoring Safety & Quality Cultures - Dave Litwiller - May 2024...Enhancing and Restoring Safety & Quality Cultures - Dave Litwiller - May 2024...
Enhancing and Restoring Safety & Quality Cultures - Dave Litwiller - May 2024...Dave Litwiller
 
0183760ssssssssssssssssssssssssssss00101011 (27).pdf
0183760ssssssssssssssssssssssssssss00101011 (27).pdf0183760ssssssssssssssssssssssssssss00101011 (27).pdf
0183760ssssssssssssssssssssssssssss00101011 (27).pdfRenandantas16
 
Business Model Canvas (BMC)- A new venture concept
Business Model Canvas (BMC)-  A new venture conceptBusiness Model Canvas (BMC)-  A new venture concept
Business Model Canvas (BMC)- A new venture conceptP&CO
 
How to Get Started in Social Media for Art League City
How to Get Started in Social Media for Art League CityHow to Get Started in Social Media for Art League City
How to Get Started in Social Media for Art League CityEric T. Tung
 

Kürzlich hochgeladen (20)

Falcon's Invoice Discounting: Your Path to Prosperity
Falcon's Invoice Discounting: Your Path to ProsperityFalcon's Invoice Discounting: Your Path to Prosperity
Falcon's Invoice Discounting: Your Path to Prosperity
 
Mondelez State of Snacking and Future Trends 2023
Mondelez State of Snacking and Future Trends 2023Mondelez State of Snacking and Future Trends 2023
Mondelez State of Snacking and Future Trends 2023
 
Mysore Call Girls 8617370543 WhatsApp Number 24x7 Best Services
Mysore Call Girls 8617370543 WhatsApp Number 24x7 Best ServicesMysore Call Girls 8617370543 WhatsApp Number 24x7 Best Services
Mysore Call Girls 8617370543 WhatsApp Number 24x7 Best Services
 
Forklift Operations: Safety through Cartoons
Forklift Operations: Safety through CartoonsForklift Operations: Safety through Cartoons
Forklift Operations: Safety through Cartoons
 
The Path to Product Excellence: Avoiding Common Pitfalls and Enhancing Commun...
The Path to Product Excellence: Avoiding Common Pitfalls and Enhancing Commun...The Path to Product Excellence: Avoiding Common Pitfalls and Enhancing Commun...
The Path to Product Excellence: Avoiding Common Pitfalls and Enhancing Commun...
 
Call Girls Electronic City Just Call 👗 7737669865 👗 Top Class Call Girl Servi...
Call Girls Electronic City Just Call 👗 7737669865 👗 Top Class Call Girl Servi...Call Girls Electronic City Just Call 👗 7737669865 👗 Top Class Call Girl Servi...
Call Girls Electronic City Just Call 👗 7737669865 👗 Top Class Call Girl Servi...
 
B.COM Unit – 4 ( CORPORATE SOCIAL RESPONSIBILITY ( CSR ).pptx
B.COM Unit – 4 ( CORPORATE SOCIAL RESPONSIBILITY ( CSR ).pptxB.COM Unit – 4 ( CORPORATE SOCIAL RESPONSIBILITY ( CSR ).pptx
B.COM Unit – 4 ( CORPORATE SOCIAL RESPONSIBILITY ( CSR ).pptx
 
BAGALUR CALL GIRL IN 98274*61493 ❤CALL GIRLS IN ESCORT SERVICE❤CALL GIRL
BAGALUR CALL GIRL IN 98274*61493 ❤CALL GIRLS IN ESCORT SERVICE❤CALL GIRLBAGALUR CALL GIRL IN 98274*61493 ❤CALL GIRLS IN ESCORT SERVICE❤CALL GIRL
BAGALUR CALL GIRL IN 98274*61493 ❤CALL GIRLS IN ESCORT SERVICE❤CALL GIRL
 
Call Girls Pune Just Call 9907093804 Top Class Call Girl Service Available
Call Girls Pune Just Call 9907093804 Top Class Call Girl Service AvailableCall Girls Pune Just Call 9907093804 Top Class Call Girl Service Available
Call Girls Pune Just Call 9907093804 Top Class Call Girl Service Available
 
FULL ENJOY Call Girls In Majnu Ka Tilla, Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Majnu Ka Tilla, Delhi Contact Us 8377877756FULL ENJOY Call Girls In Majnu Ka Tilla, Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Majnu Ka Tilla, Delhi Contact Us 8377877756
 
Call Girls In Panjim North Goa 9971646499 Genuine Service
Call Girls In Panjim North Goa 9971646499 Genuine ServiceCall Girls In Panjim North Goa 9971646499 Genuine Service
Call Girls In Panjim North Goa 9971646499 Genuine Service
 
A DAY IN THE LIFE OF A SALESMAN / WOMAN
A DAY IN THE LIFE OF A  SALESMAN / WOMANA DAY IN THE LIFE OF A  SALESMAN / WOMAN
A DAY IN THE LIFE OF A SALESMAN / WOMAN
 
Monthly Social Media Update April 2024 pptx.pptx
Monthly Social Media Update April 2024 pptx.pptxMonthly Social Media Update April 2024 pptx.pptx
Monthly Social Media Update April 2024 pptx.pptx
 
John Halpern sued for sexual assault.pdf
John Halpern sued for sexual assault.pdfJohn Halpern sued for sexual assault.pdf
John Halpern sued for sexual assault.pdf
 
Call Girls Navi Mumbai Just Call 9907093804 Top Class Call Girl Service Avail...
Call Girls Navi Mumbai Just Call 9907093804 Top Class Call Girl Service Avail...Call Girls Navi Mumbai Just Call 9907093804 Top Class Call Girl Service Avail...
Call Girls Navi Mumbai Just Call 9907093804 Top Class Call Girl Service Avail...
 
Call Girls Jp Nagar Just Call 👗 7737669865 👗 Top Class Call Girl Service Bang...
Call Girls Jp Nagar Just Call 👗 7737669865 👗 Top Class Call Girl Service Bang...Call Girls Jp Nagar Just Call 👗 7737669865 👗 Top Class Call Girl Service Bang...
Call Girls Jp Nagar Just Call 👗 7737669865 👗 Top Class Call Girl Service Bang...
 
Enhancing and Restoring Safety & Quality Cultures - Dave Litwiller - May 2024...
Enhancing and Restoring Safety & Quality Cultures - Dave Litwiller - May 2024...Enhancing and Restoring Safety & Quality Cultures - Dave Litwiller - May 2024...
Enhancing and Restoring Safety & Quality Cultures - Dave Litwiller - May 2024...
 
0183760ssssssssssssssssssssssssssss00101011 (27).pdf
0183760ssssssssssssssssssssssssssss00101011 (27).pdf0183760ssssssssssssssssssssssssssss00101011 (27).pdf
0183760ssssssssssssssssssssssssssss00101011 (27).pdf
 
Business Model Canvas (BMC)- A new venture concept
Business Model Canvas (BMC)-  A new venture conceptBusiness Model Canvas (BMC)-  A new venture concept
Business Model Canvas (BMC)- A new venture concept
 
How to Get Started in Social Media for Art League City
How to Get Started in Social Media for Art League CityHow to Get Started in Social Media for Art League City
How to Get Started in Social Media for Art League City
 

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