SlideShare uma empresa Scribd logo
1 de 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/

Mais conteúdo relacionado

Mais procurados

Mulberry: A Mobile App Development Toolkit
Mulberry: A Mobile App Development ToolkitMulberry: A Mobile App Development Toolkit
Mulberry: A Mobile App Development Toolkit
Rebecca Murphey
 
The Beauty Of Java Script V5a
The Beauty Of Java Script V5aThe Beauty Of Java Script V5a
The Beauty Of Java Script V5a
rajivmordani
 

Mais procurados (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
 

Semelhante a Taming that client side mess with Backbone.js

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
smueller_sandsmedia
 
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
girish82
 
Backbone.js Simple Tutorial
Backbone.js Simple TutorialBackbone.js Simple Tutorial
Backbone.js Simple Tutorial
추근 문
 

Semelhante a 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
 

Último

Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
vu2urc
 

Último (20)

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
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
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
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
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...
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
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
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
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
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
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?
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 

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/

Notas do Editor

  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)