SlideShare ist ein Scribd-Unternehmen logo
1 von 34
Taming that client side mess with…
About me




jarod.ferguson@gmail.com   @jarodf
Backbone.js

 Oct 2010, DocumentCloud
(Underscore.js, CoffeeScript)
What does it do?
“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.”
Who uses backbone?
But wait, this is way less code?

  $(function () {
       var count = 0;
       $('#thebutton').click(function () {
           count++;
           $("#secondview").html(count);
       });
   });
var count = 0;
$('#thebutton').click(function () {
    count++;
     if (count > 1) {
          $.ajax({
              url: '/foo/dizzle/',
              type: "POST",
              dataType: 'json',
              data: someObjects.toJSON(),
              success: function (result) {
                  if (result.status == 'Success') {
                       var html = '';
                       for (d in result.data) {
                           if (d.whatever === ‘yola') {
                                  html += "<li class='yep'>" + d.name + "</li>";
                           } else {
                                  html += "<li class='nope'>" + d.name + "</li>";
                           }
                       }
                      $("#secondview").html(html);
                      toggleHistItems(result.tabId);
                  }
                  else {
                      alert(result.status);
                   }
              },
               error: function (err) {
                     uhOh(err);
               }
          });
    } else {
         yipKiYay();
    }
});
var count = 0;
$('#thebutton').click(function () {
    count++;
     if (count > 1) {
          $.ajax({
              url: '/foo/dizzle/',
              type: "POST",
              dataType: 'json',
              data: someObjects.toJSON(),
              success: function (result) {
                  if (result.status == 'Success') {
                       var html = '';
                       for (d in result.data) {
                           if (d.whatever === ‘yola') {
                                  html += "<li class='yep'>" + d.name + "</li>";
                           } else {
                                  html += "<li class='nope'>" + d.name + "</li>";
                           }
                       }
                      $("#secondview").html(html);
                        toggleHistItems(result.tabId);
                 }
                 else {
                    alert(result.status);
                  }
              },
               error: function (err) {
                   uhOh(err);
               }
           });
      } else {
          yipKiYay();
      }
});
The jQuery Divide
Rebecca Murphy – JSConf.eu
http://www.flickr.com/photos/ppix/2305078608/
Problem Not Unique
• Avoid callback soup
• Patterns > Spaghetti
• Logic in expected place, not tied to DOM
Model
• Thing
• Business Logic
• Persistence
var Todo = Backbone.Model.extend({
   defaults: {
      content: "empty todo...",
      done: false
   },

      initialize: function() {
         if (!this.get("content")) {
           this.set({"content": this.defaults.content});
         }
      },

      toggle: function() {
         this.save({done: !this.get("done")});
      },

      clear: function() {
        this.destroy();
      }
});
Common Model Functions/Properties
•   defaults, initialize
•   get/set/unset
•   id/cid
•   custom functions
•   validate/isValid
•   save/fetch/destroy
•   url/urlRoot
Views
•   Convention tied to a box on the page
•   Handles presentation logic (Presenter?)
•   Tied to a Model or Collections
•   Listens for Model changes
•   Listens for DOM events (click, hover, etc)
var TodoView = Backbone.View.extend({
   tagName: "li",
   template: _.template($('#item-template').html()),

      events: {
          "click .check": "toggleDone",
          "dblclick label.todo-content": "edit",
          "click span.todo-destroy": "clear",
          "keypress .todo-input": "updateOnEnter",
          "blur .todo-input": "close"
      },

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

      render: function () {
          $el.html(this.template(this.model.toJSON()));
          this.input = this.$('.todo-input');
          return this;
      },

      edit: function () {
          $el.addClass("editing");
          this.input.focus();
      },
      … snipped ..
});
Templates
•   The ‘Markup’
•   Decouples UI Definition from data logic
•   Promotes reuse
•   Increased maintainability
•   Backbone doesn’t care which one you use
    – Underscore, Mustache, jsRender, jQuery etc
$.each(messages.reverse(), function(index, message) {
    $('#messageList').append(
        '<li><span class="list-title">' +
        message.userName + '</span>' +
        '<abbr class="list-timestamp" title="' +
        message.datePosted + '"></abbr>' +
        '<p class="list-text">' + message.messageText +
        '</p></li>');
    }
});
<script id="categoryTemplate" type="text/x-jquery-tmpl">
    <button class="back-btn pointer" title="Back"></button>
    <div class="title">
         ${name}
    </div>
    <ul>
         {{each(i, item) items}}
         <li class="hover" iid=${item.id}>
               <div class="title">${item.name}</div>
               <div class="desc">${item.description}</div>
         </li>
         {{/each}}
    </ul>
</script>




var fragment = $('#categoryTemplate').tmpl(category);
$(this.el).html(fragment);
Collections
•   Set of Models
•   add, remove, refresh
•   get, at, length
•   fetch
•   sorting
•   _
TV Timeout for Underscore.js
• Collections                     • Functions
   – each, any, all, find            – bind, bindAll
   – filter/select, map, reduce      – memoize, defer
• Arrays                          • Objects
   – first, last                     – keys, values
   – union, intersect                – extend, clone

   findCategory: function(id) {
       return _(this.categories()).find(function(cat){
           return cat.id == id;
       });
   },
var TodoList = Backbone.Collection.extend({
    model: Todo,
    localStorage: new Store("todos-backbone"),

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

      remaining: function () {
          return this.without.apply(this, this.done());
      },

      nextOrder: function () {
          if (!this.length) return 1;
          return this.last().get('order') + 1;
      },

      comparator: function (todo) {
          return todo.get('order');
      }
});
var accounts = new Backbone.Collection;
accounts.url = '/accounts';

accounts.fetch();
Routers
• Page Routing
• Control Flow
• Stateful, Bookmarkable
TestRouter = Backbone.Router.extend({
    routes: {
        "": "home",
        "foo": "foo",
        "bar/:name": "somefunction"
    },

      home: function () {

      },

      foo: function () {
          alert('hi from foo');
      },

      somefunction: function (name) {
          alert(name);
      }
});
Events
var object = {};

_.extend(object, Backbone.Events);

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

object.trigger("alert", "an event");
Other
• History
  – a global router (per frame) to
    handle hashchange events or pushState
  – matchs the appropriate route, and trigger callbacks
• Backbone.sync
  – method: the CRUD method
  – model: the model to be saved (or collection to be
    read)
  – options: success and error callbacks, and all other
    jQuery request options
Catalog of Events
•   "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 the
    first argument.
Advanced
• CoffeeScript
• AMD/Require.js
Get Started
Github site
http://documentcloud.github.com/backbone/

Backbone Fundamentals
https://github.com/addyosmani/backbone-
fundamentals

TodoMVC
http://addyosmani.github.com/todomvc/

Weitere ähnliche Inhalte

Was ist angesagt?

Mulberry: A Mobile App Development Toolkit
Mulberry: A Mobile App Development ToolkitMulberry: A Mobile App Development Toolkit
Mulberry: A Mobile App Development ToolkitRebecca Murphey
 
Angular.js Fundamentals
Angular.js FundamentalsAngular.js Fundamentals
Angular.js FundamentalsMark
 
Jquery In Rails
Jquery In RailsJquery In Rails
Jquery In Railsshen liu
 
DOM Scripting Toolkit - jQuery
DOM Scripting Toolkit - jQueryDOM Scripting Toolkit - jQuery
DOM Scripting Toolkit - jQueryRemy Sharp
 
The Beauty Of Java Script V5a
The Beauty Of Java Script V5aThe Beauty Of Java Script V5a
The Beauty Of Java Script V5arajivmordani
 
A New Baseline for Front-End Devs
A New Baseline for Front-End DevsA New Baseline for Front-End Devs
A New Baseline for Front-End DevsRebecca Murphey
 
AngularJS Services
AngularJS ServicesAngularJS Services
AngularJS ServicesEyal Vardi
 
History of jQuery
History of jQueryHistory of jQuery
History of jQueryjeresig
 
IndexedDB - Querying and Performance
IndexedDB - Querying and PerformanceIndexedDB - Querying and Performance
IndexedDB - Querying and PerformanceParashuram N
 
AngularJS Compile Process
AngularJS Compile ProcessAngularJS Compile Process
AngularJS Compile ProcessEyal Vardi
 
JavaScript for Flex Devs
JavaScript for Flex DevsJavaScript for Flex Devs
JavaScript for Flex DevsAaronius
 
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
 
Building Large jQuery Applications
Building Large jQuery ApplicationsBuilding Large jQuery Applications
Building Large jQuery ApplicationsRebecca Murphey
 

Was ist angesagt? (20)

Mulberry: A Mobile App Development Toolkit
Mulberry: A Mobile App Development ToolkitMulberry: A Mobile App Development Toolkit
Mulberry: A Mobile App Development Toolkit
 
Backbone js
Backbone jsBackbone js
Backbone js
 
Angular.js Fundamentals
Angular.js FundamentalsAngular.js Fundamentals
Angular.js Fundamentals
 
Jquery In Rails
Jquery In RailsJquery In Rails
Jquery In Rails
 
DOM Scripting Toolkit - jQuery
DOM Scripting Toolkit - jQueryDOM Scripting Toolkit - jQuery
DOM Scripting Toolkit - jQuery
 
Sane Async Patterns
Sane Async PatternsSane Async Patterns
Sane Async Patterns
 
The Beauty Of Java Script V5a
The Beauty Of Java Script V5aThe Beauty Of Java Script V5a
The Beauty Of Java Script V5a
 
A New Baseline for Front-End Devs
A New Baseline for Front-End DevsA New Baseline for Front-End Devs
A New Baseline for Front-End Devs
 
AngularJS Services
AngularJS ServicesAngularJS Services
AngularJS Services
 
History of jQuery
History of jQueryHistory of jQuery
History of jQuery
 
The Beauty of Java Script
The Beauty of Java ScriptThe Beauty of Java Script
The Beauty of Java Script
 
Jquery Fundamentals
Jquery FundamentalsJquery Fundamentals
Jquery Fundamentals
 
HTML,CSS Next
HTML,CSS NextHTML,CSS Next
HTML,CSS Next
 
JQuery introduction
JQuery introductionJQuery introduction
JQuery introduction
 
IndexedDB - Querying and Performance
IndexedDB - Querying and PerformanceIndexedDB - Querying and Performance
IndexedDB - Querying and Performance
 
AngularJS Compile Process
AngularJS Compile ProcessAngularJS Compile Process
AngularJS Compile Process
 
Dojo Confessions
Dojo ConfessionsDojo Confessions
Dojo Confessions
 
JavaScript for Flex Devs
JavaScript for Flex DevsJavaScript for Flex Devs
JavaScript for Flex Devs
 
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
 
Building Large jQuery Applications
Building Large jQuery ApplicationsBuilding Large jQuery Applications
Building Large jQuery Applications
 

Ähnlich wie Taming that client side mess with Backbone.js

Understanding backbonejs
Understanding backbonejsUnderstanding backbonejs
Understanding backbonejsNick Lee
 
jQuery: Tips, tricks and hints for better development and Performance
jQuery: Tips, tricks and hints for better development and PerformancejQuery: Tips, tricks and hints for better development and Performance
jQuery: Tips, tricks and hints for better development and PerformanceJonas De Smet
 
Writing Maintainable JavaScript
Writing Maintainable JavaScriptWriting Maintainable JavaScript
Writing Maintainable JavaScriptAndrew Dupont
 
international PHP2011_Bastian Feder_jQuery's Secrets
international PHP2011_Bastian Feder_jQuery's Secretsinternational PHP2011_Bastian Feder_jQuery's Secrets
international PHP2011_Bastian Feder_jQuery's Secretssmueller_sandsmedia
 
Aplicacoes dinamicas Rails com Backbone
Aplicacoes dinamicas Rails com BackboneAplicacoes dinamicas Rails com Backbone
Aplicacoes dinamicas Rails com BackboneRafael Felix da Silva
 
Advanced jQuery
Advanced jQueryAdvanced jQuery
Advanced jQuerysergioafp
 
jQuery - 10 Time-Savers You (Maybe) Don't Know
jQuery - 10 Time-Savers You (Maybe) Don't KnowjQuery - 10 Time-Savers You (Maybe) Don't Know
jQuery - 10 Time-Savers You (Maybe) Don't Knowgirish82
 
JQuery In Drupal
JQuery In DrupalJQuery In Drupal
JQuery In Drupalkatbailey
 
Javascript first-class citizenery
Javascript first-class citizeneryJavascript first-class citizenery
Javascript first-class citizenerytoddbr
 
jQuery UI Widgets, Drag and Drop, Drupal 7 Javascript
jQuery UI Widgets, Drag and Drop, Drupal 7 JavascriptjQuery UI Widgets, Drag and Drop, Drupal 7 Javascript
jQuery UI Widgets, Drag and Drop, Drupal 7 JavascriptDarren Mothersele
 
Virtual Madness @ Etsy
Virtual Madness @ EtsyVirtual Madness @ Etsy
Virtual Madness @ EtsyNishan Subedi
 
jQuery & 10,000 Global Functions: Working with Legacy JavaScript
jQuery & 10,000 Global Functions: Working with Legacy JavaScriptjQuery & 10,000 Global Functions: Working with Legacy JavaScript
jQuery & 10,000 Global Functions: Working with Legacy JavaScriptGuy Royse
 
Secrets of JavaScript Libraries
Secrets of JavaScript LibrariesSecrets of JavaScript Libraries
Secrets of JavaScript Librariesjeresig
 
Backbone.js Simple Tutorial
Backbone.js Simple TutorialBackbone.js Simple Tutorial
Backbone.js Simple Tutorial추근 문
 

Ähnlich wie Taming that client side mess with Backbone.js (20)

Understanding backbonejs
Understanding backbonejsUnderstanding backbonejs
Understanding backbonejs
 
jQuery: Tips, tricks and hints for better development and Performance
jQuery: Tips, tricks and hints for better development and PerformancejQuery: Tips, tricks and hints for better development and Performance
jQuery: Tips, tricks and hints for better development and Performance
 
Writing Maintainable JavaScript
Writing Maintainable JavaScriptWriting Maintainable JavaScript
Writing Maintainable JavaScript
 
jQuery secrets
jQuery secretsjQuery secrets
jQuery secrets
 
Clean Javascript
Clean JavascriptClean Javascript
Clean Javascript
 
international PHP2011_Bastian Feder_jQuery's Secrets
international PHP2011_Bastian Feder_jQuery's Secretsinternational PHP2011_Bastian Feder_jQuery's Secrets
international PHP2011_Bastian Feder_jQuery's Secrets
 
jQuery secrets
jQuery secretsjQuery secrets
jQuery secrets
 
Aplicacoes dinamicas Rails com Backbone
Aplicacoes dinamicas Rails com BackboneAplicacoes dinamicas Rails com Backbone
Aplicacoes dinamicas Rails com Backbone
 
jQuery introduction
jQuery introductionjQuery introduction
jQuery introduction
 
Advanced jQuery
Advanced jQueryAdvanced jQuery
Advanced jQuery
 
jQuery - 10 Time-Savers You (Maybe) Don't Know
jQuery - 10 Time-Savers You (Maybe) Don't KnowjQuery - 10 Time-Savers You (Maybe) Don't Know
jQuery - 10 Time-Savers You (Maybe) Don't Know
 
Backbone.js
Backbone.jsBackbone.js
Backbone.js
 
JQuery In Drupal
JQuery In DrupalJQuery In Drupal
JQuery In Drupal
 
Javascript first-class citizenery
Javascript first-class citizeneryJavascript first-class citizenery
Javascript first-class citizenery
 
jQuery UI Widgets, Drag and Drop, Drupal 7 Javascript
jQuery UI Widgets, Drag and Drop, Drupal 7 JavascriptjQuery UI Widgets, Drag and Drop, Drupal 7 Javascript
jQuery UI Widgets, Drag and Drop, Drupal 7 Javascript
 
Virtual Madness @ Etsy
Virtual Madness @ EtsyVirtual Madness @ Etsy
Virtual Madness @ Etsy
 
jQuery & 10,000 Global Functions: Working with Legacy JavaScript
jQuery & 10,000 Global Functions: Working with Legacy JavaScriptjQuery & 10,000 Global Functions: Working with Legacy JavaScript
jQuery & 10,000 Global Functions: Working with Legacy JavaScript
 
Secrets of JavaScript Libraries
Secrets of JavaScript LibrariesSecrets of JavaScript Libraries
Secrets of JavaScript Libraries
 
Backbone.js Simple Tutorial
Backbone.js Simple TutorialBackbone.js Simple Tutorial
Backbone.js Simple Tutorial
 
Jquery 4
Jquery 4Jquery 4
Jquery 4
 

Kürzlich hochgeladen

A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MIND CTI
 
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
 
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
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAndrey Devyatkin
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...apidays
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsRoshan Dwivedi
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...DianaGray10
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesBoston Institute of Analytics
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024The Digital Insurer
 

Kürzlich hochgeladen (20)

A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
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
 
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)
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation Strategies
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 

Taming that client side mess with Backbone.js

  • 1. Taming that client side mess with…
  • 3. Backbone.js Oct 2010, DocumentCloud (Underscore.js, CoffeeScript)
  • 4. What does it do? “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. But wait, this is way less code? $(function () { var count = 0; $('#thebutton').click(function () { count++; $("#secondview").html(count); }); });
  • 7. var count = 0; $('#thebutton').click(function () { count++; if (count > 1) { $.ajax({ url: '/foo/dizzle/', type: "POST", dataType: 'json', data: someObjects.toJSON(), success: function (result) { if (result.status == 'Success') { var html = ''; for (d in result.data) { if (d.whatever === ‘yola') { html += "<li class='yep'>" + d.name + "</li>"; } else { html += "<li class='nope'>" + d.name + "</li>"; } } $("#secondview").html(html); toggleHistItems(result.tabId); } else { alert(result.status); } }, error: function (err) { uhOh(err); } }); } else { yipKiYay(); } });
  • 8. var count = 0; $('#thebutton').click(function () { count++; if (count > 1) { $.ajax({ url: '/foo/dizzle/', type: "POST", dataType: 'json', data: someObjects.toJSON(), success: function (result) { if (result.status == 'Success') { var html = ''; for (d in result.data) { if (d.whatever === ‘yola') { html += "<li class='yep'>" + d.name + "</li>"; } else { html += "<li class='nope'>" + d.name + "</li>"; } } $("#secondview").html(html); toggleHistItems(result.tabId); } else { alert(result.status); } }, error: function (err) { uhOh(err); } }); } else { yipKiYay(); } });
  • 9. The jQuery Divide Rebecca Murphy – JSConf.eu
  • 10.
  • 12.
  • 13.
  • 14.
  • 15. Problem Not Unique • Avoid callback soup • Patterns > Spaghetti • Logic in expected place, not tied to DOM
  • 16. Model • Thing • Business Logic • Persistence
  • 17. var Todo = Backbone.Model.extend({ defaults: { content: "empty todo...", done: false }, initialize: function() { if (!this.get("content")) { this.set({"content": this.defaults.content}); } }, toggle: function() { this.save({done: !this.get("done")}); }, clear: function() { this.destroy(); } });
  • 18. Common Model Functions/Properties • defaults, initialize • get/set/unset • id/cid • custom functions • validate/isValid • save/fetch/destroy • url/urlRoot
  • 19. Views • Convention tied to a box on the page • Handles presentation logic (Presenter?) • Tied to a Model or Collections • Listens for Model changes • Listens for DOM events (click, hover, etc)
  • 20. var TodoView = Backbone.View.extend({ tagName: "li", template: _.template($('#item-template').html()), events: { "click .check": "toggleDone", "dblclick label.todo-content": "edit", "click span.todo-destroy": "clear", "keypress .todo-input": "updateOnEnter", "blur .todo-input": "close" }, initialize: function () { this.model.bind('change', this.render, this); this.model.bind('destroy', this.remove, this); }, render: function () { $el.html(this.template(this.model.toJSON())); this.input = this.$('.todo-input'); return this; }, edit: function () { $el.addClass("editing"); this.input.focus(); }, … snipped .. });
  • 21. Templates • The ‘Markup’ • Decouples UI Definition from data logic • Promotes reuse • Increased maintainability • Backbone doesn’t care which one you use – Underscore, Mustache, jsRender, jQuery etc
  • 22. $.each(messages.reverse(), function(index, message) { $('#messageList').append( '<li><span class="list-title">' + message.userName + '</span>' + '<abbr class="list-timestamp" title="' + message.datePosted + '"></abbr>' + '<p class="list-text">' + message.messageText + '</p></li>'); } });
  • 23. <script id="categoryTemplate" type="text/x-jquery-tmpl"> <button class="back-btn pointer" title="Back"></button> <div class="title"> ${name} </div> <ul> {{each(i, item) items}} <li class="hover" iid=${item.id}> <div class="title">${item.name}</div> <div class="desc">${item.description}</div> </li> {{/each}} </ul> </script> var fragment = $('#categoryTemplate').tmpl(category); $(this.el).html(fragment);
  • 24. Collections • Set of Models • add, remove, refresh • get, at, length • fetch • sorting • _
  • 25. TV Timeout for Underscore.js • Collections • Functions – each, any, all, find – bind, bindAll – filter/select, map, reduce – memoize, defer • Arrays • Objects – first, last – keys, values – union, intersect – extend, clone findCategory: function(id) { return _(this.categories()).find(function(cat){ return cat.id == id; }); },
  • 26. var TodoList = Backbone.Collection.extend({ model: Todo, localStorage: new Store("todos-backbone"), done: function () { return this.filter(function (todo) { return todo.get('done'); }); }, remaining: function () { return this.without.apply(this, this.done()); }, nextOrder: function () { if (!this.length) return 1; return this.last().get('order') + 1; }, comparator: function (todo) { return todo.get('order'); } });
  • 27. var accounts = new Backbone.Collection; accounts.url = '/accounts'; accounts.fetch();
  • 28. Routers • Page Routing • Control Flow • Stateful, Bookmarkable
  • 29. TestRouter = Backbone.Router.extend({ routes: { "": "home", "foo": "foo", "bar/:name": "somefunction" }, home: function () { }, foo: function () { alert('hi from foo'); }, somefunction: function (name) { alert(name); } });
  • 30. Events var object = {}; _.extend(object, Backbone.Events); object.on("alert", function(msg) { alert("Triggered " + msg); }); object.trigger("alert", "an event");
  • 31. Other • History – a global router (per frame) to handle hashchange events or pushState – matchs the appropriate route, and trigger callbacks • Backbone.sync – method: the CRUD method – model: the model to be saved (or collection to be read) – options: success and error callbacks, and all other jQuery request options
  • 32. Catalog of Events • "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 the first argument.
  • 34. Get Started Github site http://documentcloud.github.com/backbone/ Backbone Fundamentals https://github.com/addyosmani/backbone- fundamentals TodoMVC http://addyosmani.github.com/todomvc/

Hinweis der Redaktion

  1. Thank youQ’s- Who has used Mlibs? (jquery, prototype, mootools)- End to End frameworks? (Knockout, Ember, Spine)-Used backbone?
  2. MS Developer Advisory CouncilData Access InsiderIdaho Startup Weekend Winner
  3. A tool to know more about your documents, ppl, places and orgs, dates. Annotate, highlight &amp; share (Think publishers)
  4. A convention based JavaScript presentation framework. Its small powerful,gives you structure to build on- More than one way to do it (i.e. Respect the boundaries, model should not know about view, but some do it anyway)- Dependencies: underscore, jquery/zeptoThere is a common misconception that it is MVC, but that is inaccurate, which well talk about later.
  5. No one really important!DEMO!
  6. And down we go! Hope you have enough air….You&apos;ll be gone a whileStill not sure why you would you use bb? Lets talk about why
  7. Backbone gives us StructureJavascriptis so flexible, it makes it easy to create globs of unorganized code. I am sure most of you have experienced this.Becomes ever important as a project scales
  8. Backbone gives us ConventionConvention provides us some Familiarity, esp when working in teams, multiple projects
  9. Backbone separates concernsBusiness logic, view markup, data, persistence
  10. LightweightOnly 1200 lines of code including comments16kb
  11. Why would you use bb?- Building SPA’s or sophisticated users interfaces with plain javascript or jQuery is complicated- Quickly turn into a mess of callbacks tied to DOM elements- You can write your own framework to solve this, but that can be a lot of work. - There are many of these frameworks popping up. (knockout, ember, spine, sproutcore, batman)Lets take a look at the components of backbone
  12. Models are the heart of any application, containing the interactive data as well as a large part of the logic surrounding it: conversions, validations, computed properties, and access control. You extend Backbone.Model with your domain-specific methods, and Model provides a basic set of functionality for managing changes.
  13. Don’t get hung up on the nameBackbone views are almost more convention than they are codethey don&apos;t determine anything about your HTML or CSS for you, and can be used with any JavaScript templating library. The general idea is to organize your interface into logical views, backed by models, each of which can be updated independently when the model changes, without having to redraw the page. Instead of digging into a JSON object, looking up an element in the DOM, and updating the HTML by hand, you can bind your view&apos;s render function to the model&apos;s &quot;change&quot; event — and now everywhere that model data is displayed in the UI, it is always immediately up to date.
  14.  Basic view- el, tag, class- Event handlingscoped selector view.$, this.$\\Note render returns this for chaining- Binding model events- models &apos;change&apos;- bindAll scope (not needed)- 3rd ‘this’ arg, protip
  15. Can define in script tags, or in code. Compile for performance
  16. Collections are ordered sets of models. You can bind &quot;change&quot; events to be notified when any model in the collection has been modified, listen for &quot;add&quot; and &quot;remove&quot;events, fetch the collection from the server, and use a full suite of Underscore.js methods.
  17. Really deserves its own talk“Underscore provides 60-odd functions that support both the usual functional suspects:map, select, invoke — as well as more specialized helpers: function binding, javascripttemplating, deep equality testing, and so on”
  18. Using local storage, but could set url &amp; fetch
  19. Showing fetch from server
  20. Best way to talk about routers, isto just take a look at one.
  21. Pretty simple. DEMO!Start history.
  22. Events is a module that can be mixed in to any object, giving the object the ability to bind and trigger custom named events. Events do not have to be declared before they are bound, and may take passed arguments.Really easy to decouple objects (models &amp; views) w/ simple pub/subShow WW?
  23. Backbone.sync is the function that Backbone calls every time it attempts to read or save a model to the server. By default, it uses (jQuery/Zepto).ajax to make a RESTful JSON request and returns a jqXHR. You can override it in order to use a different persistence strategy, such as WebSockets, XML transport, or Local Storage.DEMO!
  24. Here&apos;s a list of all of the built-in events that Backbone.js can fire. You&apos;re also free to trigger your own events on Models and Views as you see fit.
  25. Async Module Definitions – Design to load modular code asynchronously (browser or server)