Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Introdução ao Backbone.js

Introdução ao Backbone.js

Avatar for arthurgeek

arthurgeek

May 03, 2012
Tweet

Other Decks in Programming

Transcript

  1. GET /contacts [ { "created_at": "2012-05-01T18:18:27Z", "updated_at": "2012-05-01T18:18:27Z", "id": 1,

    "last_name": "Simpson", "first_name": "Homer", "email": "[email protected]" }, { "created_at": "2012-05-01T18:18:37Z", "updated_at": "2012-05-01T18:18:37Z", "id": 2, "last_name": "Simpson", "first_name": "Marge", "email": "[email protected]" } ]
  2. jQuery-way $.getJSON("/contacts", function(data) { var contacts = []; $.each(data, function(index,

    contact) { var contactData = []; contactData.push("<td>" + contact.first_name + "</td>"); contactData.push("<td>" + contact.last_name + "</td>"); contactData.push("<td>" + contact.email + "</td>"); var row = $("<tr>", { id: "contact-" + contact.id, html: contactData.join("") }); contacts.push(row.get(0)); }); $("tbody").append(contacts); });
  3. jQuery-way $.getJSON("/contacts", function(data) { var contacts = []; $.each(data, function(index,

    contact) { var contactData = []; contactData.push("<td>" + contact.first_name + "</td>"); contactData.push("<td>" + contact.last_name + "</td>"); contactData.push("<td>" + contact.email + "</td>"); var row = $("<tr>", { id: "contact-" + contact.id, html: contactData.join("") }); contacts.push(row.get(0)); }); $("tbody").append(contacts); }); <tr id="contact-1"> <td>Homer</td> <td>Simpson</td> <td>[email protected]</td> </tr> <tr id="contact-2"> <td>Marge</td> <td>Simpson</td> <td>[email protected]</td> </tr>
  4. jQuery-way $(".delete").click(function() { var contactRow = $(this).closest("tr"); var id =

    contactRow.attr("id").replace("contact-", ""); $.ajax({ url:"/contacts/" + id, type:"DELETE", success: function() { contactRow.remove(); } }); });
  5. $.getJSON("/contacts", function(data) { var contacts = []; $.each(data, function(index, contact)

    { var contactData = []; contactData.push("<td>" + contact.first_name + "</td>"); contactData.push("<td>" + contact.last_name + "</td>"); contactData.push("<td>" + contact.email + "</td>"); var row = $("<tr>", { id: "contact-" + contact.id, html: contactData.join("") }); contacts.push(row.get(0)); }); $("tbody").append(contacts); }); Callback/Selectors hell
  6. $.getJSON("/contacts", function(data) { var contacts = []; $.each(data, function(index, contact)

    { var contactData = []; contactData.push("<td>" + contact.first_name + "</td>"); contactData.push("<td>" + contact.last_name + "</td>"); contactData.push("<td>" + contact.email + "</td>"); var row = $("<tr>", { id: "contact-" + contact.id, html: contactData.join("") }); contacts.push(row.get(0)); }); $("tbody").append(contacts); }); Callback/Selectors hell
  7. $.getJSON("/contacts", function(data) { var contacts = []; $.each(data, function(index, contact)

    { var contactData = []; contactData.push("<td>" + contact.first_name + "</td>"); contactData.push("<td>" + contact.last_name + "</td>"); contactData.push("<td>" + contact.email + "</td>"); var row = $("<tr>", { id: "contact-" + contact.id, html: contactData.join("") }); contacts.push(row.get(0)); }); $("tbody").append(contacts); }); Callback/Selectors hell
  8. $.getJSON("/contacts", function(data) { var contacts = []; $.each(data, function(index, contact)

    { var contactData = []; contactData.push("<td>" + contact.first_name + "</td>"); contactData.push("<td>" + contact.last_name + "</td>"); contactData.push("<td>" + contact.email + "</td>"); var row = $("<tr>", { id: "contact-" + contact.id, html: contactData.join("") }); contacts.push(row.get(0)); }); $("tbody").append(contacts); }); Callback/Selectors hell
  9. $.getJSON("/contacts", function(data) { var contacts = []; $.each(data, function(index, contact)

    { var contactData = []; contactData.push("<td>" + contact.first_name + "</td>"); contactData.push("<td>" + contact.last_name + "</td>"); contactData.push("<td>" + contact.email + "</td>"); var row = $("<tr>", { id: "contact-" + contact.id, html: contactData.join("") }); contacts.push(row.get(0)); }); $("tbody").append(contacts); }); Callback/Selectors hell $(".delete").click(function() { var contactRow = $(this).closest("tr"); var id = contactRow.attr("id").replace("contact-", ""); $.ajax({ url:"/contacts/" + id, type:"DELETE", success: function() { contactRow.remove(); } }); });
  10. $.getJSON("/contacts", function(data) { var contacts = []; $.each(data, function(index, contact)

    { var contactData = []; contactData.push("<td>" + contact.first_name + "</td>"); contactData.push("<td>" + contact.last_name + "</td>"); contactData.push("<td>" + contact.email + "</td>"); var row = $("<tr>", { id: "contact-" + contact.id, html: contactData.join("") }); contacts.push(row.get(0)); }); $("tbody").append(contacts); }); Callback/Selectors hell $(".delete").click(function() { var contactRow = $(this).closest("tr"); var id = contactRow.attr("id").replace("contact-", ""); $.ajax({ url:"/contacts/" + id, type:"DELETE", success: function() { contactRow.remove(); } }); });
  11. $.getJSON("/contacts", function(data) { var contacts = []; $.each(data, function(index, contact)

    { var contactData = []; contactData.push("<td>" + contact.first_name + "</td>"); contactData.push("<td>" + contact.last_name + "</td>"); contactData.push("<td>" + contact.email + "</td>"); var row = $("<tr>", { id: "contact-" + contact.id, html: contactData.join("") }); contacts.push(row.get(0)); }); $("tbody").append(contacts); }); Callback/Selectors hell $(".delete").click(function() { var contactRow = $(this).closest("tr"); var id = contactRow.attr("id").replace("contact-", ""); $.ajax({ url:"/contacts/" + id, type:"DELETE", success: function() { contactRow.remove(); } }); });
  12. $.getJSON("/contacts", function(data) { var contacts = []; $.each(data, function(index, contact)

    { var contactData = []; contactData.push("<td>" + contact.first_name + "</td>"); contactData.push("<td>" + contact.last_name + "</td>"); contactData.push("<td>" + contact.email + "</td>"); var row = $("<tr>", { id: "contact-" + contact.id, html: contactData.join("") }); contacts.push(row.get(0)); }); $("tbody").append(contacts); }); Callback/Selectors hell $(".delete").click(function() { var contactRow = $(this).closest("tr"); var id = contactRow.attr("id").replace("contact-", ""); $.ajax({ url:"/contacts/" + id, type:"DELETE", success: function() { contactRow.remove(); } }); });
  13. Do que precisamos? • Desacoplar os dados da UI •

    Não manipular diretamente o DOM
  14. Do que precisamos? • Desacoplar os dados da UI •

    Não manipular diretamente o DOM • Eliminar/diminuir os callbacks
  15. Do que precisamos? • Desacoplar os dados da UI •

    Não manipular diretamente o DOM • Eliminar/diminuir os callbacks • Estruturar nosso código client-side
  16. 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. Backbone.js ?
  17. 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. Backbone.js ?
  18. 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. Backbone.js ?
  19. 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. Backbone.js ?
  20. 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. Backbone.js ?
  21. 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. Backbone.js ?
  22. Backbone.js ? • Criado por Jeremy Ashkenas • Underscore.js •

    Coffeescript • Lightweight • < 6kb • Fácil de entender
  23. Backbone.js ? • Criado por Jeremy Ashkenas • Underscore.js •

    Coffeescript • Lightweight • < 6kb • Fácil de entender • 1239 LOC
  24. Backbone.js ? • Criado por Jeremy Ashkenas • Underscore.js •

    Coffeescript • Lightweight • < 6kb • Fácil de entender • 1239 LOC • Muito bem documentado
  25. Backbone.js ? • Criado por Jeremy Ashkenas • Underscore.js •

    Coffeescript • Lightweight • < 6kb • Fácil de entender • 1239 LOC • Muito bem documentado • http://documentcloud.github.com/backbone/docs/backbone.html
  26. Backbone.js ? • Criado por Jeremy Ashkenas • Underscore.js •

    Coffeescript • Lightweight • < 6kb • Fácil de entender • 1239 LOC • Muito bem documentado • http://documentcloud.github.com/backbone/docs/backbone.html • MVC-style
  27. Backbone.js ? • Criado por Jeremy Ashkenas • Underscore.js •

    Coffeescript • Lightweight • < 6kb • Fácil de entender • 1239 LOC • Muito bem documentado • http://documentcloud.github.com/backbone/docs/backbone.html • MVC-style • Model, View, ViewController
  28. Backbone.js ? • Criado por Jeremy Ashkenas • Underscore.js •

    Coffeescript • Lightweight • < 6kb • Fácil de entender • 1239 LOC • Muito bem documentado • http://documentcloud.github.com/backbone/docs/backbone.html • MVC-style • Model, View, ViewController • Poucas dependências
  29. Backbone.js ? • Criado por Jeremy Ashkenas • Underscore.js •

    Coffeescript • Lightweight • < 6kb • Fácil de entender • 1239 LOC • Muito bem documentado • http://documentcloud.github.com/backbone/docs/backbone.html • MVC-style • Model, View, ViewController • Poucas dependências • Underscore.js
  30. Backbone.js ? • Criado por Jeremy Ashkenas • Underscore.js •

    Coffeescript • Lightweight • < 6kb • Fácil de entender • 1239 LOC • Muito bem documentado • http://documentcloud.github.com/backbone/docs/backbone.html • MVC-style • Model, View, ViewController • Poucas dependências • Underscore.js • jQuery ou Zepto.js
  31. MVC? •Model • Backbone.Model / Backbone.Collection •View • Templates •

    Underscore.js, Handlebars, Mustache.js, etc •Controller • Backbone.View / Backbone.Router
  32. Backbone.Model • Representa seus Dados • Validações • Persistência App.Models.Contact

    = Backbone.Model.extend({ urlRoot: "/contacts" }); var bart = new Contact({ first_name: "Bart", last_name: "Simpson", email: "[email protected]" }); bart.save(); // POST /contacts bart.set("email", "[email protected]"); bart.save(); // PUT /contacts/1 bart.destroy(); // DELETE /contacts/1
  33. Backbone.Model • Representa seus Dados • Validações • Persistência App.Models.Contact

    = Backbone.Model.extend({ urlRoot: "/contacts" }); var bart = new Contact({ first_name: "Bart", last_name: "Simpson", email: "[email protected]" }); bart.save(); // POST /contacts bart.set("email", "[email protected]"); bart.save(); // PUT /contacts/1 bart.destroy(); // DELETE /contacts/1
  34. Backbone.Model • Representa seus Dados • Validações • Persistência App.Models.Contact

    = Backbone.Model.extend({ urlRoot: "/contacts" }); var bart = new Contact({ first_name: "Bart", last_name: "Simpson", email: "[email protected]" }); bart.save(); // POST /contacts bart.set("email", "[email protected]"); bart.save(); // PUT /contacts/1 bart.destroy(); // DELETE /contacts/1
  35. Backbone.Model • Representa seus Dados • Validações • Persistência App.Models.Contact

    = Backbone.Model.extend({ urlRoot: "/contacts" }); var bart = new Contact({ first_name: "Bart", last_name: "Simpson", email: "[email protected]" }); bart.save(); // POST /contacts bart.set("email", "[email protected]"); bart.save(); // PUT /contacts/1 bart.destroy(); // DELETE /contacts/1
  36. Backbone.Model • Representa seus Dados • Validações • Persistência App.Models.Contact

    = Backbone.Model.extend({ urlRoot: "/contacts" }); var bart = new Contact({ first_name: "Bart", last_name: "Simpson", email: "[email protected]" }); bart.save(); // POST /contacts bart.set("email", "[email protected]"); bart.save(); // PUT /contacts/1 bart.destroy(); // DELETE /contacts/1
  37. Backbone.Model • Representa seus Dados • Validações • Persistência App.Models.Contact

    = Backbone.Model.extend({ urlRoot: "/contacts" }); var bart = new Contact({ first_name: "Bart", last_name: "Simpson", email: "[email protected]" }); bart.save(); // POST /contacts bart.set("email", "[email protected]"); bart.save(); // PUT /contacts/1 bart.destroy(); // DELETE /contacts/1
  38. Backbone.Collection • Array de modelos • Métodos utilitários (underscore.js) App.Collections.Contact

    = Backbone.Collection.extend({ model: App.Models.Contact, url: "/contacts" }); var contacts = new App.Collections.Contact(); contacts.fetch(); // GET /contacts var arthur = contacts.create({ first_name: "Arthur", last_name: "Zapparoli", email: "[email protected]" }); // POST /contacts var familyNames = contacts.pluck("last_name"); var simpsons = contacts.filter(function(contact) { return contact.get("last_name") === "Simpson"; });
  39. Backbone.Collection • Array de modelos • Métodos utilitários (underscore.js) App.Collections.Contact

    = Backbone.Collection.extend({ model: App.Models.Contact, url: "/contacts" }); var contacts = new App.Collections.Contact(); contacts.fetch(); // GET /contacts var arthur = contacts.create({ first_name: "Arthur", last_name: "Zapparoli", email: "[email protected]" }); // POST /contacts var familyNames = contacts.pluck("last_name"); var simpsons = contacts.filter(function(contact) { return contact.get("last_name") === "Simpson"; });
  40. Backbone.Collection • Array de modelos • Métodos utilitários (underscore.js) App.Collections.Contact

    = Backbone.Collection.extend({ model: App.Models.Contact, url: "/contacts" }); var contacts = new App.Collections.Contact(); contacts.fetch(); // GET /contacts var arthur = contacts.create({ first_name: "Arthur", last_name: "Zapparoli", email: "[email protected]" }); // POST /contacts var familyNames = contacts.pluck("last_name"); var simpsons = contacts.filter(function(contact) { return contact.get("last_name") === "Simpson"; });
  41. Backbone.Collection • Array de modelos • Métodos utilitários (underscore.js) App.Collections.Contact

    = Backbone.Collection.extend({ model: App.Models.Contact, url: "/contacts" }); var contacts = new App.Collections.Contact(); contacts.fetch(); // GET /contacts var arthur = contacts.create({ first_name: "Arthur", last_name: "Zapparoli", email: "[email protected]" }); // POST /contacts var familyNames = contacts.pluck("last_name"); var simpsons = contacts.filter(function(contact) { return contact.get("last_name") === "Simpson"; });
  42. Backbone.Collection • Array de modelos • Métodos utilitários (underscore.js) App.Collections.Contact

    = Backbone.Collection.extend({ model: App.Models.Contact, url: "/contacts" }); var contacts = new App.Collections.Contact(); contacts.fetch(); // GET /contacts var arthur = contacts.create({ first_name: "Arthur", last_name: "Zapparoli", email: "[email protected]" }); // POST /contacts var familyNames = contacts.pluck("last_name"); var simpsons = contacts.filter(function(contact) { return contact.get("last_name") === "Simpson"; });
  43. Backbone.View • Controller • Trata os eventos do DOM •

    Renderiza um Model ou Collection App.Views.Contacts = Backbone.View.extend({ el: "#contacts" }); App.Views.Contact = Backbone.View.extend({ tagName: "tr", template: _.template($("#contact-template").html()), render: function() { this.$el.html(this.template(this.model.toJSON())); return this; } }); contactView = new App.Views.Contact({model: homer}); $("tbody").append(contactView.render().el);
  44. Backbone.View • Controller • Trata os eventos do DOM •

    Renderiza um Model ou Collection App.Views.Contacts = Backbone.View.extend({ el: $("#contacts") }); App.Views.Contact = Backbone.View.extend({ tagName: "tr", template: _.template($("#contact-template").html()), render: function() { this.$el.html(this.template(this.model.toJSON())); return this; } }); contactView = new App.Views.Contact({model: homer}); $("tbody").append(contactView.render().el);
  45. Backbone.View • Controller • Trata os eventos do DOM •

    Renderiza um Model ou Collection App.Views.Contacts = Backbone.View.extend({ el: $("#contacts") }); App.Views.Contact = Backbone.View.extend({ tagName: "tr", template: _.template($("#contact-template").html()), render: function() { this.$el.html(this.template(this.model.toJSON())); return this; } }); contactView = new App.Views.Contact({model: homer}); $("tbody").append(contactView.render().el);
  46. Backbone.View • Controller • Trata os eventos do DOM •

    Renderiza um Model ou Collection App.Views.Contacts = Backbone.View.extend({ el: $("#contacts") }); App.Views.Contact = Backbone.View.extend({ tagName: "tr", template: _.template($("#contact-template").html()), render: function() { this.$el.html(this.template(this.model.toJSON())); return this; } }); contactView = new App.Views.Contact({model: homer}); $("tbody").append(contactView.render().el);
  47. Backbone.Router • Mapeia URLs para funções • HTML5 pushState-ready App.Router

    = Backbone.Router.extend({ routes: { "": "home", "/contact/:id": "showContact" }, home: function() { // Carrega a collection e renderiza a View na tela }, showContact: function(id) { // Carrega o model e renderiza a View na tela } });
  48. Backbone.Events App.Views.Contact = Backbone.View.extend({ events: { "click .delete": "destroy" },

    destroy: function() { this.model.destroy(); } }); Respondendo a eventos do DOM
  49. Backbone.Events Respondendo a eventos do Model/Collection App.Views.Contacts = Backbone.View.extend({ initialize:

    function() { this.collection.on("add", this.addOne, this); this.collection.on("reset", this.addAll, this); }, addOne: function(contact) { var view = new App.Views.Contact({ model: contact }); this.$("tbody").append(view.render().el); }, addAll: function() { this.collection.each(this.addOne); } }); App.Views.Contact = Backbone.View.extend({ initialize: function() { this.model.on("change", this.render, this); this.model.on("destroy", this.remove, this); } });