SlideShare une entreprise Scribd logo
1  sur  32
Backbone.js
What it is, what it does, and why we use it at Usable.
Backbone.js
• Not a magic bullet.
• Not tiny once you make it useful (139kb).
• Not perfect, some things are hard.
• Not suitable for some applications.
Backbone.js
• MVC - Model,View, Controller
• (Backbone.js calls the controller a Router)
• Collections, Sync, History, and more
• Underscore.js, json2.js, jQuery (or Zepto)
Backbone.js
Models - Objects that represent a thing.


 • Models are objects
 • Core of Backbone.js
 • Contains an array of attributes
 • Listens for events
Backbone.js
Models - Objects that represent a thing.

var Cat = Backbone.Model.extend({

      defaults: {
           name: ‘Cat’,
           breed: 'Moggy',
           colour: ‘Ginger’,
           legs: 4
      },

      initialize: function(data) {

      },
});
Backbone.js
Using a model - Getting attributes.

var Purrkins = new Cat({
    name: ‘Purrkins’,
});




console.log(Purrkins.get(“breed”)); //Moggy




console.log(Purrkins.get(“colour”)); //Ginger




console.log(Purrkins.get(“name”)); //Purrkins
Backbone.js
Using a model - Setting attributes.

Purrkins.set({name:‘Mister Purrkins’, age: 6});




console.log(Purrkins.get(“name”)); //Mister Purrkins
Backbone.js
Using a model - Saving.


 • Saving a model is easy
 • Backbone Sync
 • Restful interface - GET, POST, PUT, DELETE
 • Up to you to write the server side stuff
Backbone.js
Using a model - Saving to an API.

var Cat = Backbone.Model.extend({

      url: ‘/api/cat/’,

      defaults: {
           name: ‘Cat’,
           breed: 'Moggy',
           colour: ‘Ginger’,
           legs: 4
      },

      initialize: function(data) {

      },
});
Backbone.js
Using a model - Saving to an API.

Purrkins.save({name:‘Mister Purrkins’, age: 6});




POST http://localhost/api/cat/
PAYLOAD: {
    "name":"Mister Purrkins",
    "breed":"Moggy",
    "colour":"Ginger",
    "legs":4,
    “age”: 6
}
Backbone.js
Using a model - Validating.


 • Should you just save everything?
 • Models need to be validated
 • No helper functions for validation
 • Underscore.js provides some
Backbone.js
Using a model - Validating before saving.

var Cat = Backbone.Model.extend({

      url: ‘/api/cat/’,

      defaults: {
           name: ‘Cat’,
           breed: 'Moggy',
           colour: ‘Ginger’,
           legs: 4
      },

      initialize: function(data) {

      },

      validate: function(attrs) {
           var errors = {};
           if (attrs.age < 5) {
               errors.age = ‘Must be below 5’;
           }
           if (!_.isEmpty(errors)) {
               errors.invalid = true;
               return errors;
           }
      },

});
Backbone.js
Using a model - Validating before saving.

Purrkins.save(
    {age: 6},
    success: function(){ console.log(‘Kitty saved’); },
    error: function(model,error){
        if (error.invalid==true) {
            $.each(_.keys(error), function(i,el){
                console.log(el+”:”+error[el]);
            });
        } else {
            console.log(“Error status: ”+error.status);
            console.log(“Error response: ”+error.responseText);
        }
    }
);



age:Must be below 5
Backbone.js
Using a model - API errors.

Purrkins.save(
    {age: 4},
    success: function(){ console.log(‘Kitty saved’); },
    error: function(model,error){
        if (error.invalid==true) {
            $.each(_.keys(error), function(i,el){
                console.log(el+”:”+error[el]);
            });
        } else {
            console.log(“Error status: ”+error.status);
            console.log(“Error response: ”+error.responseText);
        }
    }
);



Error status: 500
Error response: Internal Server Error - Database not found
Backbone.js
Collections - Groups of objects.


 • Collections are ‘arrays’ of models
 • Add, push, shift, pop, unshift, etc
 • Built on Underscore.js
 • Filter, sort, etc
Backbone.js
Collections - Groups of objects.

var Glaring = Backbone.Collection.extend({

      model: Cat

});




Collective noun for a group of cats: a glaring
Backbone.js
Using a collection - Adding models.

var CrazyCatLady = new Glaring([
    {id: 1, name: ‘Purrkins’, legs: 3},
    {id: 2, name: ‘Napoleon’, colour:‘Tabby’},
    {id: 3, name: ‘Josey’, colour:‘Tabby’, legs: 100},
    {id: 4, name: ‘Coco’, breed:‘Siamese’, colour:‘Chocolate’},
    {id: 5, name: ‘Charlie’},
]);




console.log(CrazyCatLady.get(2).get(“name”)); //Napoleon




CrazyCatLady.add({id: 6, name: ‘Augustus’});




console.log(CrazyCatLady.get(6).get(“name”)); //Augustus
Backbone.js
Using a collection - Underscore.js rocks.

var TabbyCats = CrazyCatLady.where({colour: “Tabby”);




console.log(TabbyCats); //Napoleon, Josey




var fourorfivelegs = CrazyCatLady.filter(function(Cat){
    var legs = cat.get(“legs”);
    return (legs > 3 && legs < 6);
});




console.log(fourorfivelegs); //Napoleon, Coco, Charlie, Augustus




var names = CrazyCatLady.pluck(“name”);




console.log(names); //Purrkins, Napoleon, Josey, Coco, Charlie, Augustus
Backbone.js
Views - Displaying a model.


 • Views are not HTML
 • Views are a description of a model
 • The HTML code comes from templates
 • Works with any template system
Backbone.js
Views - Displaying a model.

var Catview = Backbone.View.extend({

      initialize: function() {
         _.bindAll( this, 'render' )
      },

      render: function() {

           this.$el.html(templates.catview(this.model.toJSON()));

           return this;

      },

});




var c = new Catview({model: CrazyCatLady.get(1) });
$(‘div#cat’).html(c.render().el);
Backbone.js
Views - Displaying a collection.


 • Collections can have views
 • Actually a view containing views
 • Nested? Sort of.
 • Think in terms of partials/blocks
Backbone.js
Views - Displaying a collection.

var CatRowView = Backbone.View.extend({

  tagName:     "div",

  initialize: function() {
     _.bindAll( this, 'render' )
     this.model.bind('change', this.render, this);
  },

  render: function() {

       this.$el.html(templates.catrowview(this.model.toJSON()));
       return this;

  },
});
Backbone.js
Views - Displaying a collection.

var CatListView = Backbone.View.extend({

  initialize: function(data) {

       this.collection = data.collection;

       this.collection.bind('add', this.addOne, this);
       this.collection.bind('all', this.render, this);

       this.collection.each(this.addOne);

  },

  render: function() {

  },

  addOne: function(cat) {
     var view = new CatRowView({model:cat});
     $("div#cats").append(view.render().el);
  },
});
Backbone.js
Views - Displaying a collection.

var catslisting = new CatListView({collection: CrazyCatLady});




CatListView

   CatRowView   -   Purrkins
   CatRowView   -   Napoleon
   CatRowView   -   Josey
   CatRowView   -   Coco
   CatRowView   -   Charlie
   CatRowView   -   Augustus
Backbone.js
Views - Binding events.


 • Views are not just about displaying things
 • Binding events to View elements
 • Stuff happens when you click things
 • Or double click, press a key, whatever
Backbone.js
Views - Binding events.

var Catview = Backbone.View.extend({

      initialize: function() {
         _.bindAll( this, 'render' )
      },

      events: {
         "click a.edit": "edit",
      },

      render: function() {

           this.$el.html(templates.catview(this.model.toJSON()));
           return this;

      },

      edit: function(){
        app.navigate('#/cats/'+this.model.id, true);
      }

});
Backbone.js
Routing - Backbone.js’ controller.

var Router = Backbone.Router.extend({

      routes: {

           “/cats”: “cats”,
           “/cats/:catid”: “catview”,
           “*path”: “default”,

      },

      cats: function(){
          //Something to do with cats
      },
      catview: function(catid){
          //Something to do with a specific cat
      },
      default: function(path){
          //Everything else
      }

});
Backbone.js
Routing - Backbone.js’ controller.

 cats: function(){
     var catlisting = new CatList({ collection: CrazyCatLady });
     $('div#content').html(catlisting.render().el);

 },




 catview: function(id){
     var catview = new CatView({ model: CrazyCatLady.get(id) });
     $('div#content').html(catview.render().el);

 },




 default: function(path){
     var template = path.substr(1); //strip the initial /
     if (template=='') { template = 'base'; }
     ui.display(path, template);
 },
Backbone.js
History - Handling hashchange events

Backbone.history.start();




Important notes:

• Must start after the router object.
• Must start after the HTML is done. Wrap it in
your favourite flavour of jQuery.ready();
• If you can get pushState to work, tell me how.
Backbone.js
Who’s using it?


 • UsableHQ (that’s me!)
 • Foursquare, Stripe, DocumentCloud
 • LinkedIn, Basecamp, AirBnB (for mobile)
 • Flow, Wunderkit, Khan Academy
“Don’t let the perfect be the enemy of the good.”
                                             Voltaire
Chris Neale
Technical Director, UsableHQ



    chris@usablehq.com


        @usablehq
      or @onion2k

Contenu connexe

Tendances

Google guava overview
Google guava overviewGoogle guava overview
Google guava overviewSteve Min
 
JavaScript and the AST
JavaScript and the ASTJavaScript and the AST
JavaScript and the ASTJarrod Overson
 
Google Guava - Core libraries for Java & Android
Google Guava - Core libraries for Java & AndroidGoogle Guava - Core libraries for Java & Android
Google Guava - Core libraries for Java & AndroidJordi Gerona
 
Keeping It Small with Slim
Keeping It Small with SlimKeeping It Small with Slim
Keeping It Small with SlimRaven Tools
 
Drupal & javascript
Drupal & javascriptDrupal & javascript
Drupal & javascriptAlmog Baku
 
Akka and the Zen of Reactive System Design
Akka and the Zen of Reactive System DesignAkka and the Zen of Reactive System Design
Akka and the Zen of Reactive System DesignLightbend
 
Zepto.js, a jQuery-compatible mobile JavaScript framework in 2K
Zepto.js, a jQuery-compatible mobile JavaScript framework in 2KZepto.js, a jQuery-compatible mobile JavaScript framework in 2K
Zepto.js, a jQuery-compatible mobile JavaScript framework in 2KThomas Fuchs
 
Arquitetando seu aplicativo Android com Jetpack
Arquitetando seu aplicativo Android com JetpackArquitetando seu aplicativo Android com Jetpack
Arquitetando seu aplicativo Android com JetpackNelson Glauber Leal
 
Intro To Moose
Intro To MooseIntro To Moose
Intro To MoosecPanel
 
Less ismorewithcoffeescript webdirectionsfeb2012
Less ismorewithcoffeescript webdirectionsfeb2012Less ismorewithcoffeescript webdirectionsfeb2012
Less ismorewithcoffeescript webdirectionsfeb2012Jo Cranford
 
Assetic (Symfony Live Paris)
Assetic (Symfony Live Paris)Assetic (Symfony Live Paris)
Assetic (Symfony Live Paris)Kris Wallsmith
 
AST - the only true tool for building JavaScript
AST - the only true tool for building JavaScriptAST - the only true tool for building JavaScript
AST - the only true tool for building JavaScriptIngvar Stepanyan
 
Moose workshop
Moose workshopMoose workshop
Moose workshopYnon Perek
 
Coffeescript: No really, it's just Javascript
Coffeescript: No really, it's just JavascriptCoffeescript: No really, it's just Javascript
Coffeescript: No really, it's just JavascriptBrian Mann
 
Proxies are Awesome!
Proxies are Awesome!Proxies are Awesome!
Proxies are Awesome!Brendan Eich
 

Tendances (20)

Drupal 8: Fields reborn
Drupal 8: Fields rebornDrupal 8: Fields reborn
Drupal 8: Fields reborn
 
Google guava overview
Google guava overviewGoogle guava overview
Google guava overview
 
JavaScript and the AST
JavaScript and the ASTJavaScript and the AST
JavaScript and the AST
 
Google Guava - Core libraries for Java & Android
Google Guava - Core libraries for Java & AndroidGoogle Guava - Core libraries for Java & Android
Google Guava - Core libraries for Java & Android
 
Keeping It Small with Slim
Keeping It Small with SlimKeeping It Small with Slim
Keeping It Small with Slim
 
Drupal & javascript
Drupal & javascriptDrupal & javascript
Drupal & javascript
 
Akka and the Zen of Reactive System Design
Akka and the Zen of Reactive System DesignAkka and the Zen of Reactive System Design
Akka and the Zen of Reactive System Design
 
Zepto.js, a jQuery-compatible mobile JavaScript framework in 2K
Zepto.js, a jQuery-compatible mobile JavaScript framework in 2KZepto.js, a jQuery-compatible mobile JavaScript framework in 2K
Zepto.js, a jQuery-compatible mobile JavaScript framework in 2K
 
Google Guava
Google GuavaGoogle Guava
Google Guava
 
ES2015 workflows
ES2015 workflowsES2015 workflows
ES2015 workflows
 
Arquitetando seu aplicativo Android com Jetpack
Arquitetando seu aplicativo Android com JetpackArquitetando seu aplicativo Android com Jetpack
Arquitetando seu aplicativo Android com Jetpack
 
Intro To Moose
Intro To MooseIntro To Moose
Intro To Moose
 
jQuery Loves You
jQuery Loves YoujQuery Loves You
jQuery Loves You
 
Less ismorewithcoffeescript webdirectionsfeb2012
Less ismorewithcoffeescript webdirectionsfeb2012Less ismorewithcoffeescript webdirectionsfeb2012
Less ismorewithcoffeescript webdirectionsfeb2012
 
Assetic (Symfony Live Paris)
Assetic (Symfony Live Paris)Assetic (Symfony Live Paris)
Assetic (Symfony Live Paris)
 
AST - the only true tool for building JavaScript
AST - the only true tool for building JavaScriptAST - the only true tool for building JavaScript
AST - the only true tool for building JavaScript
 
Moose workshop
Moose workshopMoose workshop
Moose workshop
 
Coffeescript: No really, it's just Javascript
Coffeescript: No really, it's just JavascriptCoffeescript: No really, it's just Javascript
Coffeescript: No really, it's just Javascript
 
Your JavaScript Library
Your JavaScript LibraryYour JavaScript Library
Your JavaScript Library
 
Proxies are Awesome!
Proxies are Awesome!Proxies are Awesome!
Proxies are Awesome!
 

En vedette

Introduction To Backbone JS
Introduction To Backbone JSIntroduction To Backbone JS
Introduction To Backbone JSparamisoft
 
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
 
Backbone.js
Backbone.jsBackbone.js
Backbone.jstonyskn
 

En vedette (7)

Backbone Basics with Examples
Backbone Basics with ExamplesBackbone Basics with Examples
Backbone Basics with Examples
 
Introduction To Backbone JS
Introduction To Backbone JSIntroduction To Backbone JS
Introduction To 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
 
Backbone.js
Backbone.jsBackbone.js
Backbone.js
 

Similaire à Backbone.js

Understanding backbonejs
Understanding backbonejsUnderstanding backbonejs
Understanding backbonejsNick Lee
 
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
 
Backbone.js Simple Tutorial
Backbone.js Simple TutorialBackbone.js Simple Tutorial
Backbone.js Simple Tutorial추근 문
 
前端MVC 豆瓣说
前端MVC 豆瓣说前端MVC 豆瓣说
前端MVC 豆瓣说Ting Lv
 
¿Cómo de sexy puede hacer Backbone mi código?
¿Cómo de sexy puede hacer Backbone mi código?¿Cómo de sexy puede hacer Backbone mi código?
¿Cómo de sexy puede hacer Backbone mi código?jaespinmora
 
Aplicacoes dinamicas Rails com Backbone
Aplicacoes dinamicas Rails com BackboneAplicacoes dinamicas Rails com Backbone
Aplicacoes dinamicas Rails com BackboneRafael Felix da Silva
 
Impress Your Friends with EcmaScript 2015
Impress Your Friends with EcmaScript 2015Impress Your Friends with EcmaScript 2015
Impress Your Friends with EcmaScript 2015Lukas Ruebbelke
 
Building Smart Async Functions For Mobile
Building Smart Async Functions For MobileBuilding Smart Async Functions For Mobile
Building Smart Async Functions For MobileGlan Thomas
 
Introducing Assetic: Asset Management for PHP 5.3
Introducing Assetic: Asset Management for PHP 5.3Introducing Assetic: Asset Management for PHP 5.3
Introducing Assetic: Asset Management for PHP 5.3Kris Wallsmith
 
Art of Javascript
Art of JavascriptArt of Javascript
Art of JavascriptTarek Yehia
 
Virtual Madness @ Etsy
Virtual Madness @ EtsyVirtual Madness @ Etsy
Virtual Madness @ EtsyNishan Subedi
 
Javascript MVC & Backbone Tips & Tricks
Javascript MVC & Backbone Tips & TricksJavascript MVC & Backbone Tips & Tricks
Javascript MVC & Backbone Tips & TricksHjörtur Hilmarsson
 
Introducing Assetic (NYPHP)
Introducing Assetic (NYPHP)Introducing Assetic (NYPHP)
Introducing Assetic (NYPHP)Kris Wallsmith
 
jQuery Data Manipulate API - A source code dissecting journey
jQuery Data Manipulate API - A source code dissecting journeyjQuery Data Manipulate API - A source code dissecting journey
jQuery Data Manipulate API - A source code dissecting journeyHuiyi Yan
 
Stop Making Excuses and Start Testing Your JavaScript
Stop Making Excuses and Start Testing Your JavaScriptStop Making Excuses and Start Testing Your JavaScript
Stop Making Excuses and Start Testing Your JavaScriptRyan Anklam
 

Similaire à Backbone.js (20)

Understanding backbonejs
Understanding backbonejsUnderstanding backbonejs
Understanding backbonejs
 
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
 
Backbone.js Simple Tutorial
Backbone.js Simple TutorialBackbone.js Simple Tutorial
Backbone.js Simple Tutorial
 
Backbone intro
Backbone introBackbone intro
Backbone intro
 
前端MVC 豆瓣说
前端MVC 豆瓣说前端MVC 豆瓣说
前端MVC 豆瓣说
 
¿Cómo de sexy puede hacer Backbone mi código?
¿Cómo de sexy puede hacer Backbone mi código?¿Cómo de sexy puede hacer Backbone mi código?
¿Cómo de sexy puede hacer Backbone mi código?
 
Aplicacoes dinamicas Rails com Backbone
Aplicacoes dinamicas Rails com BackboneAplicacoes dinamicas Rails com Backbone
Aplicacoes dinamicas Rails com Backbone
 
Impress Your Friends with EcmaScript 2015
Impress Your Friends with EcmaScript 2015Impress Your Friends with EcmaScript 2015
Impress Your Friends with EcmaScript 2015
 
Building Smart Async Functions For Mobile
Building Smart Async Functions For MobileBuilding Smart Async Functions For Mobile
Building Smart Async Functions For Mobile
 
Assetic (Zendcon)
Assetic (Zendcon)Assetic (Zendcon)
Assetic (Zendcon)
 
Introducing Assetic: Asset Management for PHP 5.3
Introducing Assetic: Asset Management for PHP 5.3Introducing Assetic: Asset Management for PHP 5.3
Introducing Assetic: Asset Management for PHP 5.3
 
Art of Javascript
Art of JavascriptArt of Javascript
Art of Javascript
 
Virtual Madness @ Etsy
Virtual Madness @ EtsyVirtual Madness @ Etsy
Virtual Madness @ Etsy
 
Assetic (OSCON)
Assetic (OSCON)Assetic (OSCON)
Assetic (OSCON)
 
Backbone js
Backbone jsBackbone js
Backbone js
 
Javascript MVC & Backbone Tips & Tricks
Javascript MVC & Backbone Tips & TricksJavascript MVC & Backbone Tips & Tricks
Javascript MVC & Backbone Tips & Tricks
 
Introducing Assetic (NYPHP)
Introducing Assetic (NYPHP)Introducing Assetic (NYPHP)
Introducing Assetic (NYPHP)
 
Say It With Javascript
Say It With JavascriptSay It With Javascript
Say It With Javascript
 
jQuery Data Manipulate API - A source code dissecting journey
jQuery Data Manipulate API - A source code dissecting journeyjQuery Data Manipulate API - A source code dissecting journey
jQuery Data Manipulate API - A source code dissecting journey
 
Stop Making Excuses and Start Testing Your JavaScript
Stop Making Excuses and Start Testing Your JavaScriptStop Making Excuses and Start Testing Your JavaScript
Stop Making Excuses and Start Testing Your JavaScript
 

Dernier

Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessPixlogix Infotech
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?Antenna Manufacturer Coco
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEarley Information Science
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CVKhem
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 

Dernier (20)

Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 

Backbone.js

  • 1. Backbone.js What it is, what it does, and why we use it at Usable.
  • 2. Backbone.js • Not a magic bullet. • Not tiny once you make it useful (139kb). • Not perfect, some things are hard. • Not suitable for some applications.
  • 3. Backbone.js • MVC - Model,View, Controller • (Backbone.js calls the controller a Router) • Collections, Sync, History, and more • Underscore.js, json2.js, jQuery (or Zepto)
  • 4. Backbone.js Models - Objects that represent a thing. • Models are objects • Core of Backbone.js • Contains an array of attributes • Listens for events
  • 5. Backbone.js Models - Objects that represent a thing. var Cat = Backbone.Model.extend({ defaults: { name: ‘Cat’, breed: 'Moggy', colour: ‘Ginger’, legs: 4 }, initialize: function(data) { }, });
  • 6. Backbone.js Using a model - Getting attributes. var Purrkins = new Cat({ name: ‘Purrkins’, }); console.log(Purrkins.get(“breed”)); //Moggy console.log(Purrkins.get(“colour”)); //Ginger console.log(Purrkins.get(“name”)); //Purrkins
  • 7. Backbone.js Using a model - Setting attributes. Purrkins.set({name:‘Mister Purrkins’, age: 6}); console.log(Purrkins.get(“name”)); //Mister Purrkins
  • 8. Backbone.js Using a model - Saving. • Saving a model is easy • Backbone Sync • Restful interface - GET, POST, PUT, DELETE • Up to you to write the server side stuff
  • 9. Backbone.js Using a model - Saving to an API. var Cat = Backbone.Model.extend({ url: ‘/api/cat/’, defaults: { name: ‘Cat’, breed: 'Moggy', colour: ‘Ginger’, legs: 4 }, initialize: function(data) { }, });
  • 10. Backbone.js Using a model - Saving to an API. Purrkins.save({name:‘Mister Purrkins’, age: 6}); POST http://localhost/api/cat/ PAYLOAD: { "name":"Mister Purrkins", "breed":"Moggy", "colour":"Ginger", "legs":4, “age”: 6 }
  • 11. Backbone.js Using a model - Validating. • Should you just save everything? • Models need to be validated • No helper functions for validation • Underscore.js provides some
  • 12. Backbone.js Using a model - Validating before saving. var Cat = Backbone.Model.extend({ url: ‘/api/cat/’, defaults: { name: ‘Cat’, breed: 'Moggy', colour: ‘Ginger’, legs: 4 }, initialize: function(data) { }, validate: function(attrs) { var errors = {}; if (attrs.age < 5) { errors.age = ‘Must be below 5’; } if (!_.isEmpty(errors)) { errors.invalid = true; return errors; } }, });
  • 13. Backbone.js Using a model - Validating before saving. Purrkins.save( {age: 6}, success: function(){ console.log(‘Kitty saved’); }, error: function(model,error){ if (error.invalid==true) { $.each(_.keys(error), function(i,el){ console.log(el+”:”+error[el]); }); } else { console.log(“Error status: ”+error.status); console.log(“Error response: ”+error.responseText); } } ); age:Must be below 5
  • 14. Backbone.js Using a model - API errors. Purrkins.save( {age: 4}, success: function(){ console.log(‘Kitty saved’); }, error: function(model,error){ if (error.invalid==true) { $.each(_.keys(error), function(i,el){ console.log(el+”:”+error[el]); }); } else { console.log(“Error status: ”+error.status); console.log(“Error response: ”+error.responseText); } } ); Error status: 500 Error response: Internal Server Error - Database not found
  • 15. Backbone.js Collections - Groups of objects. • Collections are ‘arrays’ of models • Add, push, shift, pop, unshift, etc • Built on Underscore.js • Filter, sort, etc
  • 16. Backbone.js Collections - Groups of objects. var Glaring = Backbone.Collection.extend({ model: Cat }); Collective noun for a group of cats: a glaring
  • 17. Backbone.js Using a collection - Adding models. var CrazyCatLady = new Glaring([ {id: 1, name: ‘Purrkins’, legs: 3}, {id: 2, name: ‘Napoleon’, colour:‘Tabby’}, {id: 3, name: ‘Josey’, colour:‘Tabby’, legs: 100}, {id: 4, name: ‘Coco’, breed:‘Siamese’, colour:‘Chocolate’}, {id: 5, name: ‘Charlie’}, ]); console.log(CrazyCatLady.get(2).get(“name”)); //Napoleon CrazyCatLady.add({id: 6, name: ‘Augustus’}); console.log(CrazyCatLady.get(6).get(“name”)); //Augustus
  • 18. Backbone.js Using a collection - Underscore.js rocks. var TabbyCats = CrazyCatLady.where({colour: “Tabby”); console.log(TabbyCats); //Napoleon, Josey var fourorfivelegs = CrazyCatLady.filter(function(Cat){ var legs = cat.get(“legs”); return (legs > 3 && legs < 6); }); console.log(fourorfivelegs); //Napoleon, Coco, Charlie, Augustus var names = CrazyCatLady.pluck(“name”); console.log(names); //Purrkins, Napoleon, Josey, Coco, Charlie, Augustus
  • 19. Backbone.js Views - Displaying a model. • Views are not HTML • Views are a description of a model • The HTML code comes from templates • Works with any template system
  • 20. Backbone.js Views - Displaying a model. var Catview = Backbone.View.extend({ initialize: function() { _.bindAll( this, 'render' ) }, render: function() { this.$el.html(templates.catview(this.model.toJSON())); return this; }, }); var c = new Catview({model: CrazyCatLady.get(1) }); $(‘div#cat’).html(c.render().el);
  • 21. Backbone.js Views - Displaying a collection. • Collections can have views • Actually a view containing views • Nested? Sort of. • Think in terms of partials/blocks
  • 22. Backbone.js Views - Displaying a collection. var CatRowView = Backbone.View.extend({ tagName: "div", initialize: function() { _.bindAll( this, 'render' ) this.model.bind('change', this.render, this); }, render: function() { this.$el.html(templates.catrowview(this.model.toJSON())); return this; }, });
  • 23. Backbone.js Views - Displaying a collection. var CatListView = Backbone.View.extend({ initialize: function(data) { this.collection = data.collection; this.collection.bind('add', this.addOne, this); this.collection.bind('all', this.render, this); this.collection.each(this.addOne); }, render: function() { }, addOne: function(cat) { var view = new CatRowView({model:cat}); $("div#cats").append(view.render().el); }, });
  • 24. Backbone.js Views - Displaying a collection. var catslisting = new CatListView({collection: CrazyCatLady}); CatListView CatRowView - Purrkins CatRowView - Napoleon CatRowView - Josey CatRowView - Coco CatRowView - Charlie CatRowView - Augustus
  • 25. Backbone.js Views - Binding events. • Views are not just about displaying things • Binding events to View elements • Stuff happens when you click things • Or double click, press a key, whatever
  • 26. Backbone.js Views - Binding events. var Catview = Backbone.View.extend({ initialize: function() { _.bindAll( this, 'render' ) }, events: { "click a.edit": "edit", }, render: function() { this.$el.html(templates.catview(this.model.toJSON())); return this; }, edit: function(){ app.navigate('#/cats/'+this.model.id, true); } });
  • 27. Backbone.js Routing - Backbone.js’ controller. var Router = Backbone.Router.extend({ routes: { “/cats”: “cats”, “/cats/:catid”: “catview”, “*path”: “default”, }, cats: function(){ //Something to do with cats }, catview: function(catid){ //Something to do with a specific cat }, default: function(path){ //Everything else } });
  • 28. Backbone.js Routing - Backbone.js’ controller. cats: function(){ var catlisting = new CatList({ collection: CrazyCatLady }); $('div#content').html(catlisting.render().el); }, catview: function(id){ var catview = new CatView({ model: CrazyCatLady.get(id) }); $('div#content').html(catview.render().el); }, default: function(path){ var template = path.substr(1); //strip the initial / if (template=='') { template = 'base'; } ui.display(path, template); },
  • 29. Backbone.js History - Handling hashchange events Backbone.history.start(); Important notes: • Must start after the router object. • Must start after the HTML is done. Wrap it in your favourite flavour of jQuery.ready(); • If you can get pushState to work, tell me how.
  • 30. Backbone.js Who’s using it? • UsableHQ (that’s me!) • Foursquare, Stripe, DocumentCloud • LinkedIn, Basecamp, AirBnB (for mobile) • Flow, Wunderkit, Khan Academy
  • 31. “Don’t let the perfect be the enemy of the good.” Voltaire
  • 32. Chris Neale Technical Director, UsableHQ chris@usablehq.com @usablehq or @onion2k

Notes de l'éditeur

  1. \n
  2. \n
  3. \n
  4. \n
  5. \n
  6. \n
  7. \n
  8. \n
  9. \n
  10. \n
  11. \n
  12. \n
  13. \n
  14. \n
  15. \n
  16. \n
  17. \n
  18. \n
  19. \n
  20. \n
  21. \n
  22. \n
  23. \n
  24. \n
  25. \n
  26. \n
  27. \n
  28. \n
  29. \n
  30. \n
  31. \n
  32. \n