SlideShare une entreprise Scribd logo
1  sur  31
Télécharger pour lire hors ligne
backbone.js
  and single-page web apps
             http://backbonejs.org/




Bert Wijnants - Mobile Vikings - 9 november 2012
Let's start with a little history
Javascript was invented by Netscape in 1995,
and the web looked like...
iteractive website:
<marquee>, <blink>
the rise of AJAX (2004)




gmail is the first single-page web app
more and more javascript
a website is:
lots of html pages with some javascript
ajax returns html

a webapp is:
lots of javascript with some html pages
ajax returns json

front-end is taking over program logic
necessary to create highly responsive user interfaces
#7



     6 in top 7 on Github is javascript
Why another framework?
     we've got jQuery, right?
What's wrong with jQuery?
jQuery is very useful for DOM manipulations,
events, ajax,... (cross-browser)
and btw: use zepto.js for mobile devices (webkit only)


DOM manipulation = very expensive task
breaks hardware acceleration
always avoid unnecessary DOM manipulations
especially on mobile devices


Too easy to use the DOM for state of your app
How to avoid DOM manipulations?


              important rule
          The DOM is write-only!


 don't use it to store the state of your app
   it's for presentation purposes only
Bad:

$(".button").click( function(event) {
     if (!$(this).hasClass("selected")) {
           $(this).parent().find(".button.selected").removeClass("selected);
           $(this).addClass("selected")
     }
});




Don't read from the DOM to know which of the buttons is
selected
But where to store everything
if DOM is not allowed?
Here backbone.js kicks in...
backbone.js
every good framework has "a sentence" :-)


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.


Single-page web apps with hundreds of lines of javascript.
Most apps just give structure with namespaces:
var namespace = (function() {
      return {
           ....
      }
})();                                               We need more
                                                    structure than this!
backbone.js
Pretty mature
started 2 years ago
popular on github
version 0.9.2, 1.0 coming up
from the creators of underscore.js and coffeescript

Lightweight
just 2 dependencies: underscore, jquery/zepto

Also runs on node.js
Same models in front-end and back-end
Annotated source
MVC framework or whatever
it's not really MVC, it's MVVM!

Model
View
ViewModel (=DOM)

where is the controller?
skinny controller, fat model
program logic in models and views
DOM                                          Model




                          MODEL
      html   javascript   is the only source of truth!
                          is pure javascript
                          Models and Collections
                          Collection is an array of Models
Events
Lots of events are fired
with these naming conventions:
"add" (model, collection) — when a model is added to a collection.
"remove" (model, collection) — when a model is removed from a collection.
"reset" (collection) — when the collection's entire contents have been replaced.
"change" (model, options) — when a model's attributes have changed.
"change:[attribute]" (model, value, options) — when a specific attribute has been updated.
"destroy" (model, collection) — when a model is destroyed.
"sync" (model, collection) — triggers whenever a model has been successfully synced to the server.
"error" (model, collection) — when a model's validation fails, or a save call fails on the server.
"route:[name]" (router) — when one of a router's routes has matched.
"all" — this special event fires for any triggered event, passing the event name as first argument.
render                                change events




DOM                           View                             Model
      html events                                change data




                                     VIEW
                                     observes model changes
      html       javascript
                                     is pure javascript
                                     render function to write to DOM
                                     this.el is the element in DOM
                                     observes events from DOM
                                     (click, touchmove, ...)
Model-backed views
var model = new Todo({
    title: 'foo',
    done: false
});
var view = new TodoView(model);



View has direct access to model.
Model does not. View listens to change events.
Persistency a.k.a the database
javascript applications usually work like this:

get_all()
get_one()
save_one()
update_one()
delete_one()



and the same on server-side: CRUD
Lots of code for repetitive operations
Sync
Backbone.js has a sync module

CRUD interface
GET /model
GET /model/<id>
POST /model
UPDATE /model/id
DELETE /model/id


can be overwritten granularly. examples:
use localstorage for all fetch operations
use sockets instead of REST over http
render                       change events




DOM                           View                   Model
      html events                     change data



                                                             sync




                                                      web
                                                     service
      html       javascript




                                     SYNC
                                     asynchronous persistency
Model.sync
In a Model or Collection:
fetch()
save()
remove()

don't care about what's going on in the back
More stuff:
Model validation on client-side
you can only save() a valid model

Router
easy url handling (with # or #!)
works with History API, so back button works

Underscore functions
map, reduce, for each, client-side templates, ...
example: Model
var Todo = Backbone.Model.extend({
     defaults: {
         "title" : "(empty)",
         "done" : false
     },
     toggle: function() {
         this.set({
               "done" : !this.get("done")
         });
         this.save();
     },
     clear: function() {
         this.destroy();
     }
});
example: Collection
var TodoList = Backbone.Collection.extend({
     model: Todo,

      initialize: function() {
            this.fetch();
      },

      done: function() {
         return this.filter(function(todo){ return todo.get('done'); });
      },

      remaining: function() {
         return this.without.apply(this, this.done());
      },
});
example: View
var TodoView = Backbone.View.extend({
     tagName: "li",
     template: Templates.todo,

      initialize: function() {
            this.model.bind('change', this.render, this);
            this.model.bind('destroy', this.remove, this);
      },
      render: function() {
            this.$el.html(this.template(this.model.toJSON()));
            this.$el.toggleClass('done', this.model.get('done'));
            return this;
      }
});
example: View (continued)
events: {
   "click .toggle" : "toggleDone",
   "click .clear" : "clear"
},

toggleDone: function() {
    this.model.toggle();
},

clear: function() {
    this.model.clear();
}
Problems
Syntax is not very clear
Lots of ( { "
=> coffeescript can help with this

The use of this
you loose scope quite easily in javascript
=> var self = this to the rescue

Steep learning curve
but documentation is very good
lots of support on stackoverflow
Advantages
structured javascript
write-only DOM
designed for web apps
syncing with back-end = trivial
naming conventions (events, render, ...)
model change => view render
very popular: big community
Getting started

http://backbonejs.org
Everything you need is here

Or check out the webapp for VikingSpots NG:
github.com/deals-platform/mobile-apps/html5




                                Questions? Remarks?

Contenu connexe

Tendances

AngularJS Architecture
AngularJS ArchitectureAngularJS Architecture
AngularJS ArchitectureEyal Vardi
 
Javascript Module Patterns
Javascript Module PatternsJavascript Module Patterns
Javascript Module PatternsNicholas Jansma
 
【前端Mvc】之豆瓣说实践
【前端Mvc】之豆瓣说实践【前端Mvc】之豆瓣说实践
【前端Mvc】之豆瓣说实践taobao.com
 
Intro to BackboneJS + Intermediate Javascript
Intro to BackboneJS + Intermediate JavascriptIntro to BackboneJS + Intermediate Javascript
Intro to BackboneJS + Intermediate JavascriptAndrew Lovett-Barron
 
Creating the interfaces of the future with the APIs of today
Creating the interfaces of the future with the APIs of todayCreating the interfaces of the future with the APIs of today
Creating the interfaces of the future with the APIs of todaygerbille
 
Intro to Ember.js
Intro to Ember.jsIntro to Ember.js
Intro to Ember.jsJay Phelps
 
Workshop 12: AngularJS Parte I
Workshop 12: AngularJS Parte IWorkshop 12: AngularJS Parte I
Workshop 12: AngularJS Parte IVisual Engineering
 
Swift Delhi: Practical POP
Swift Delhi: Practical POPSwift Delhi: Practical POP
Swift Delhi: Practical POPNatasha Murashev
 
Ajax on drupal the right way - DrupalCamp Campinas, São Paulo, Brazil 2016
Ajax on drupal the right way - DrupalCamp Campinas, São Paulo, Brazil 2016Ajax on drupal the right way - DrupalCamp Campinas, São Paulo, Brazil 2016
Ajax on drupal the right way - DrupalCamp Campinas, São Paulo, Brazil 2016Nicolás Bouhid
 
JavaScript for Flex Devs
JavaScript for Flex DevsJavaScript for Flex Devs
JavaScript for Flex DevsAaronius
 
Javascript first-class citizenery
Javascript first-class citizeneryJavascript first-class citizenery
Javascript first-class citizenerytoddbr
 
AngularJS Compile Process
AngularJS Compile ProcessAngularJS Compile Process
AngularJS Compile ProcessEyal Vardi
 
Client Side MVC & Angular
Client Side MVC & AngularClient Side MVC & Angular
Client Side MVC & AngularAlexe Bogdan
 
AngularJS Directives
AngularJS DirectivesAngularJS Directives
AngularJS DirectivesEyal Vardi
 
AngularJS for designers and developers
AngularJS for designers and developersAngularJS for designers and developers
AngularJS for designers and developersKai Koenig
 
Dependency Management with RequireJS
Dependency Management with RequireJSDependency Management with RequireJS
Dependency Management with RequireJSAaronius
 

Tendances (20)

AngularJS Architecture
AngularJS ArchitectureAngularJS Architecture
AngularJS Architecture
 
Javascript Module Patterns
Javascript Module PatternsJavascript Module Patterns
Javascript Module Patterns
 
【前端Mvc】之豆瓣说实践
【前端Mvc】之豆瓣说实践【前端Mvc】之豆瓣说实践
【前端Mvc】之豆瓣说实践
 
Intro to BackboneJS + Intermediate Javascript
Intro to BackboneJS + Intermediate JavascriptIntro to BackboneJS + Intermediate Javascript
Intro to BackboneJS + Intermediate Javascript
 
Creating the interfaces of the future with the APIs of today
Creating the interfaces of the future with the APIs of todayCreating the interfaces of the future with the APIs of today
Creating the interfaces of the future with the APIs of today
 
Intro to Ember.js
Intro to Ember.jsIntro to Ember.js
Intro to Ember.js
 
Workshop 12: AngularJS Parte I
Workshop 12: AngularJS Parte IWorkshop 12: AngularJS Parte I
Workshop 12: AngularJS Parte I
 
Swift Delhi: Practical POP
Swift Delhi: Practical POPSwift Delhi: Practical POP
Swift Delhi: Practical POP
 
Ajax on drupal the right way - DrupalCamp Campinas, São Paulo, Brazil 2016
Ajax on drupal the right way - DrupalCamp Campinas, São Paulo, Brazil 2016Ajax on drupal the right way - DrupalCamp Campinas, São Paulo, Brazil 2016
Ajax on drupal the right way - DrupalCamp Campinas, São Paulo, Brazil 2016
 
JavaScript for Flex Devs
JavaScript for Flex DevsJavaScript for Flex Devs
JavaScript for Flex Devs
 
Javascript first-class citizenery
Javascript first-class citizeneryJavascript first-class citizenery
Javascript first-class citizenery
 
React
React React
React
 
AngularJS Compile Process
AngularJS Compile ProcessAngularJS Compile Process
AngularJS Compile Process
 
DrupalCon jQuery
DrupalCon jQueryDrupalCon jQuery
DrupalCon jQuery
 
Backbone js
Backbone jsBackbone js
Backbone js
 
Client Side MVC & Angular
Client Side MVC & AngularClient Side MVC & Angular
Client Side MVC & Angular
 
AngularJS Directives
AngularJS DirectivesAngularJS Directives
AngularJS Directives
 
AngularJS for designers and developers
AngularJS for designers and developersAngularJS for designers and developers
AngularJS for designers and developers
 
jQuery: Events, Animation, Ajax
jQuery: Events, Animation, AjaxjQuery: Events, Animation, Ajax
jQuery: Events, Animation, Ajax
 
Dependency Management with RequireJS
Dependency Management with RequireJSDependency Management with RequireJS
Dependency Management with RequireJS
 

Similaire à Viking academy backbone.js

Javascript frameworks: Backbone.js
Javascript frameworks: Backbone.jsJavascript frameworks: Backbone.js
Javascript frameworks: Backbone.jsSoós Gábor
 
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
 
The Theory Of The Dom
The Theory Of The DomThe Theory Of The Dom
The Theory Of The Domkaven yan
 
Developing maintainable Cordova applications
Developing maintainable Cordova applicationsDeveloping maintainable Cordova applications
Developing maintainable Cordova applicationsIvano Malavolta
 
WebNet Conference 2012 - Designing complex applications using html5 and knock...
WebNet Conference 2012 - Designing complex applications using html5 and knock...WebNet Conference 2012 - Designing complex applications using html5 and knock...
WebNet Conference 2012 - Designing complex applications using html5 and knock...Fabio Franzini
 
Backbone JS for mobile apps
Backbone JS for mobile appsBackbone JS for mobile apps
Backbone JS for mobile appsIvano Malavolta
 
Patterns Are Good For Managers
Patterns Are Good For ManagersPatterns Are Good For Managers
Patterns Are Good For ManagersAgileThought
 
HTML5 for the Silverlight Guy
HTML5 for the Silverlight GuyHTML5 for the Silverlight Guy
HTML5 for the Silverlight GuyDavid Padbury
 
Rp 6 session 2 naresh bhatia
Rp 6  session 2 naresh bhatiaRp 6  session 2 naresh bhatia
Rp 6 session 2 naresh bhatiasapientindia
 
Backbone/Marionette introduction
Backbone/Marionette introductionBackbone/Marionette introduction
Backbone/Marionette introductionmatt-briggs
 
Intro to React - Featuring Modern JavaScript
Intro to React - Featuring Modern JavaScriptIntro to React - Featuring Modern JavaScript
Intro to React - Featuring Modern JavaScriptjasonsich
 
MV* presentation frameworks in Javascript: en garde, pret, allez!
MV* presentation frameworks in Javascript: en garde, pret, allez!MV* presentation frameworks in Javascript: en garde, pret, allez!
MV* presentation frameworks in Javascript: en garde, pret, allez!Roberto Messora
 
jquery summit presentation for large scale javascript applications
jquery summit  presentation for large scale javascript applicationsjquery summit  presentation for large scale javascript applications
jquery summit presentation for large scale javascript applicationsDivyanshGupta922023
 
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
 

Similaire à Viking academy backbone.js (20)

Javascript frameworks: Backbone.js
Javascript frameworks: Backbone.jsJavascript frameworks: Backbone.js
Javascript frameworks: 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
 
Backbone.js
Backbone.jsBackbone.js
Backbone.js
 
The Theory Of The Dom
The Theory Of The DomThe Theory Of The Dom
The Theory Of The Dom
 
Developing maintainable Cordova applications
Developing maintainable Cordova applicationsDeveloping maintainable Cordova applications
Developing maintainable Cordova applications
 
WebNet Conference 2012 - Designing complex applications using html5 and knock...
WebNet Conference 2012 - Designing complex applications using html5 and knock...WebNet Conference 2012 - Designing complex applications using html5 and knock...
WebNet Conference 2012 - Designing complex applications using html5 and knock...
 
Backbone Basics with Examples
Backbone Basics with ExamplesBackbone Basics with Examples
Backbone Basics with Examples
 
Backbone JS for mobile apps
Backbone JS for mobile appsBackbone JS for mobile apps
Backbone JS for mobile apps
 
Patterns Are Good For Managers
Patterns Are Good For ManagersPatterns Are Good For Managers
Patterns Are Good For Managers
 
HTML5 for the Silverlight Guy
HTML5 for the Silverlight GuyHTML5 for the Silverlight Guy
HTML5 for the Silverlight Guy
 
Rp 6 session 2 naresh bhatia
Rp 6  session 2 naresh bhatiaRp 6  session 2 naresh bhatia
Rp 6 session 2 naresh bhatia
 
Backbone/Marionette introduction
Backbone/Marionette introductionBackbone/Marionette introduction
Backbone/Marionette introduction
 
[2015/2016] Backbone JS
[2015/2016] Backbone JS[2015/2016] Backbone JS
[2015/2016] Backbone JS
 
Intro to React - Featuring Modern JavaScript
Intro to React - Featuring Modern JavaScriptIntro to React - Featuring Modern JavaScript
Intro to React - Featuring Modern JavaScript
 
BackboneJS + ReactJS
BackboneJS + ReactJSBackboneJS + ReactJS
BackboneJS + ReactJS
 
MV* presentation frameworks in Javascript: en garde, pret, allez!
MV* presentation frameworks in Javascript: en garde, pret, allez!MV* presentation frameworks in Javascript: en garde, pret, allez!
MV* presentation frameworks in Javascript: en garde, pret, allez!
 
Backbone.js
Backbone.jsBackbone.js
Backbone.js
 
jquery summit presentation for large scale javascript applications
jquery summit  presentation for large scale javascript applicationsjquery summit  presentation for large scale javascript applications
jquery summit presentation for large scale javascript applications
 
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
 

Viking academy backbone.js

  • 1. backbone.js and single-page web apps http://backbonejs.org/ Bert Wijnants - Mobile Vikings - 9 november 2012
  • 2. Let's start with a little history Javascript was invented by Netscape in 1995, and the web looked like...
  • 4. the rise of AJAX (2004) gmail is the first single-page web app
  • 5. more and more javascript a website is: lots of html pages with some javascript ajax returns html a webapp is: lots of javascript with some html pages ajax returns json front-end is taking over program logic necessary to create highly responsive user interfaces
  • 6. #7 6 in top 7 on Github is javascript
  • 7. Why another framework? we've got jQuery, right?
  • 8. What's wrong with jQuery? jQuery is very useful for DOM manipulations, events, ajax,... (cross-browser) and btw: use zepto.js for mobile devices (webkit only) DOM manipulation = very expensive task breaks hardware acceleration always avoid unnecessary DOM manipulations especially on mobile devices Too easy to use the DOM for state of your app
  • 9. How to avoid DOM manipulations? important rule The DOM is write-only! don't use it to store the state of your app it's for presentation purposes only
  • 10. Bad: $(".button").click( function(event) { if (!$(this).hasClass("selected")) { $(this).parent().find(".button.selected").removeClass("selected); $(this).addClass("selected") } }); Don't read from the DOM to know which of the buttons is selected
  • 11. But where to store everything if DOM is not allowed? Here backbone.js kicks in...
  • 12. backbone.js every good framework has "a sentence" :-) 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. Single-page web apps with hundreds of lines of javascript. Most apps just give structure with namespaces: var namespace = (function() { return { .... } })(); We need more structure than this!
  • 13. backbone.js Pretty mature started 2 years ago popular on github version 0.9.2, 1.0 coming up from the creators of underscore.js and coffeescript Lightweight just 2 dependencies: underscore, jquery/zepto Also runs on node.js Same models in front-end and back-end
  • 15. MVC framework or whatever it's not really MVC, it's MVVM! Model View ViewModel (=DOM) where is the controller? skinny controller, fat model program logic in models and views
  • 16. DOM Model MODEL html javascript is the only source of truth! is pure javascript Models and Collections Collection is an array of Models
  • 17. Events Lots of events are fired with these naming conventions: "add" (model, collection) — when a model is added to a collection. "remove" (model, collection) — when a model is removed from a collection. "reset" (collection) — when the collection's entire contents have been replaced. "change" (model, options) — when a model's attributes have changed. "change:[attribute]" (model, value, options) — when a specific attribute has been updated. "destroy" (model, collection) — when a model is destroyed. "sync" (model, collection) — triggers whenever a model has been successfully synced to the server. "error" (model, collection) — when a model's validation fails, or a save call fails on the server. "route:[name]" (router) — when one of a router's routes has matched. "all" — this special event fires for any triggered event, passing the event name as first argument.
  • 18. render change events DOM View Model html events change data VIEW observes model changes html javascript is pure javascript render function to write to DOM this.el is the element in DOM observes events from DOM (click, touchmove, ...)
  • 19. Model-backed views var model = new Todo({ title: 'foo', done: false }); var view = new TodoView(model); View has direct access to model. Model does not. View listens to change events.
  • 20. Persistency a.k.a the database javascript applications usually work like this: get_all() get_one() save_one() update_one() delete_one() and the same on server-side: CRUD Lots of code for repetitive operations
  • 21. Sync Backbone.js has a sync module CRUD interface GET /model GET /model/<id> POST /model UPDATE /model/id DELETE /model/id can be overwritten granularly. examples: use localstorage for all fetch operations use sockets instead of REST over http
  • 22. render change events DOM View Model html events change data sync web service html javascript SYNC asynchronous persistency
  • 23. Model.sync In a Model or Collection: fetch() save() remove() don't care about what's going on in the back
  • 24. More stuff: Model validation on client-side you can only save() a valid model Router easy url handling (with # or #!) works with History API, so back button works Underscore functions map, reduce, for each, client-side templates, ...
  • 25. example: Model var Todo = Backbone.Model.extend({ defaults: { "title" : "(empty)", "done" : false }, toggle: function() { this.set({ "done" : !this.get("done") }); this.save(); }, clear: function() { this.destroy(); } });
  • 26. example: Collection var TodoList = Backbone.Collection.extend({ model: Todo, initialize: function() { this.fetch(); }, done: function() { return this.filter(function(todo){ return todo.get('done'); }); }, remaining: function() { return this.without.apply(this, this.done()); }, });
  • 27. example: View var TodoView = Backbone.View.extend({ tagName: "li", template: Templates.todo, initialize: function() { this.model.bind('change', this.render, this); this.model.bind('destroy', this.remove, this); }, render: function() { this.$el.html(this.template(this.model.toJSON())); this.$el.toggleClass('done', this.model.get('done')); return this; } });
  • 28. example: View (continued) events: { "click .toggle" : "toggleDone", "click .clear" : "clear" }, toggleDone: function() { this.model.toggle(); }, clear: function() { this.model.clear(); }
  • 29. Problems Syntax is not very clear Lots of ( { " => coffeescript can help with this The use of this you loose scope quite easily in javascript => var self = this to the rescue Steep learning curve but documentation is very good lots of support on stackoverflow
  • 30. Advantages structured javascript write-only DOM designed for web apps syncing with back-end = trivial naming conventions (events, render, ...) model change => view render very popular: big community
  • 31. Getting started http://backbonejs.org Everything you need is here Or check out the webapp for VikingSpots NG: github.com/deals-platform/mobile-apps/html5 Questions? Remarks?