Understanding backbonejs

2,414 views
2,304 views

Published on

Understanding Backbone.js

Published in: Technology
0 Comments
1 Like
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total views
2,414
On SlideShare
0
From Embeds
0
Number of Embeds
0
Actions
Shares
0
Downloads
119
Comments
0
Likes
1
Embeds 0
No embeds

No notes for slide

Understanding backbonejs

  1. 1. Client-side MVC with Backbone.js Jquery to Backbone.js
  2. 2. Agenda• Why Backbone.js• Architecture• Jquery to Backbone.js• Real World Examples• Resources• Extras• Questions
  3. 3. Why backbonejs• From server-side to client-side• From server-side to client-side We need efficient tools• Jquery is cool but…
  4. 4. Why backbone.js• We have to store object informations into the DOM var list = ""; $.each(data, function (index, value) { list += "<li id="item-" + value.Id + "">" + value.Name + "</li>"; }); $("ul").append(list);
  5. 5. Callback helljQuery callback hell $.getJSON("/Items", function (data) { var list = ""; $.each(data, function (index, value) { list += "<li id="item-" + value.Id + "">" + value.Name + "</li>"; } ); $("ul").append(list); $("li").click(function () { var $this = $(this); var id = $this.attr("id").replace("item-", ""); $.post("/Items", { id: id }, function () { $this.fadeOut(function () { $this.remove(); }); }); });
  6. 6. Why Backbone.js“Its all too easy to create JavaScript applications that end up as tangled piles of Jquery selectors and callbacks.”• So, what do we need?• Abstraction.• Decoupling UI from Data.• No more callbacks.
  7. 7. Why Backbone.js• A RESTful service based data layer.• Events (to keep UI and data up-to-date).• A template engine.• A solid routing system.• All the above things wrapped into a lightweight JavaScript framework.
  8. 8. Architecture• Oct 13th, 2010 Jeremy Ashkenas• http://documentcloud.github.com/backbone• https://github.com/documentcloud/backbone• @documentcloud• #documentcloud on IRC• https://groups.google.com/forum/#!forum/ba ckbonejs
  9. 9. Architecture• 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.
  10. 10. Dependencies• jQuery or Zepto• Underscore.js• Json2.js
  11. 11. MVC• Model / Collection• Template (View)• View (Controller)• Router
  12. 12. Model• Representing data (auto-generated).• Handling persistence.• Throws events.• Reusable.
  13. 13. Model• Fetch HTTP GET /url• Save (new) HTTP POST /url• Save HTTP PUT /url/id• Destroy HTTP DELETE /url/id
  14. 14. Modelvar Item = Backbone.Model.extend({ idAttribute: “Id”, urlRoot: “/Items”});
  15. 15. Modelvar item = new Item();item.set({ Name: “Nick” }); // trigger changeitem.save(); // trigger sync
  16. 16. Modelhttp://backbonejs.org/#Model
  17. 17. Collection• A list of models.• Underscore methods.
  18. 18. Collectionvar Items = Backbone.Collection.extend({ model: Item, url: "/Items“});var items = new Items();items.fetch(); // trigger resetitems.comparator = function(item) { return item.get("Name");}
  19. 19. Collectionhttp://backbonejs.org/#Collection
  20. 20. View• Manipulates the DOM.• Delegates DOM events.• Has a Model / Collection.
  21. 21. Viewvar ListView = Backbone.View.extend({ el: $("ul"), initialize: function() { this.collection.bind("reset", this.render, this); }, render: function() { this.collection.each(this.addItem, this); return this; },
  22. 22. addItem: function(item) { var itemView = new ItemView({ var ItemView = Backbone.View.extend({ model: item tagName: "li", }); render: function() { this.$el.append(itemView.el); this.$el.text(this.model.get("Name")); itemView.render(); return this; } } });});
  23. 23. Viewvar items = new Items();var listView = new ListView({ collection: items});items.fetch();
  24. 24. Viewhttp://backbonejs.org/#View
  25. 25. Template(Underscore.js)Compiles JavaScript templates into functions that can be evaluated for rendering.• Mustache• jQuery - tmpl
  26. 26. Template<script type = “text/template” id = “item-template” > <li><%= Name %></li></script>var ItemView = Backbone.View.extend({ … template: _.template($("#item-template").html()), ... render: function() { this.$el.html(this.template(this.model.toJSON())); return this; } …});
  27. 27. Router• Maps urls to function.• Enable history / bookmarking.var AppRouter = Backbone.Router.extend({ routes: { "": "init" }, init: function() { … }});
  28. 28. Routerwindow.AppRouter = Backbone.Router.extend({ routes: { "": "loadInvoices", "/add": "addInvoice", "/show/:id": "showInvoice", "/edit/:id": "editInvoice" }, loadInvoices: function() {… }, addInvoice: function() {… }, showInvoice: function(id) {… }, editInvoice: function(id) {… }});
  29. 29. Routerhttp://backbonejs.org/#Router
  30. 30. Architecture
  31. 31. Jquery to Backbone.js$(document).ready(function() { $(#new-status form).submit(function(e) { e.preventDefault(); $.ajax({ url: /status, type: POST, dataType: json, data: { text: $(#new-status).find(textarea).val() }, success: function(data) { $(#statuses).append(<li> + data.text + </li>); $(#new-status).find(textarea).val(); } }); });});
  32. 32. Step to step from Jquery tovar Status = Backbone.Model.extend({ Backbone.js url: /status});var Statuses = Backbone.Collection.extend({ model: Status});var NewStatusView = Backbone.View.extend({ events: { submit form: addStatus }, initialize: function() { this.collection.on(add, this.clearInput, this); }, addStatus: function(e) { e.preventDefault(); this.collection.create({ text: this.$(textarea).val() }); }, clearInput: function() { this.$(textarea).val(); }});
  33. 33. var StatusesView = Backbone.View.extend({ initialize: function() { this.collection.on(add, this.appendStatus, this); }, appendStatus: function(status) { this.$(ul).append(<li> + status.escape(text) + </li>); }});$(document).ready(function() { var statuses = new Statuses(); new NewStatusView({ el: $(#new-status), collection: statuses }); new StatusesView({ el: $(#statuses), collection: statuses });});
  34. 34. Real World• DocumdentCloud• LinkedIn mobile• Pandora• Airbnb• Hulu• BaseCamp• Diasporahttp://backbonejs.org/#examples
  35. 35. Resource• https://github.com/documentcloud/backbone /wiki• https://github.com/documentcloud/backbone /wiki/Extensions%2C-Plugins%2C-Resources• http://backbonetutorials.com/• http://addyosmani.github.com/backbone- fundamentals/
  36. 36. ExtraTDD – Jasminehttp://pivotal.github.com/jasmine/describe("Todo", function() { it("Should have a title", function() { var todo = new Todo(); expect(todo.get("title")).toBeDefined(); });});
  37. 37. Pros and Cons+• Lightweight• Powerful• Code is clean(and maintainable)-• Too verbose(for small applications)
  38. 38. Questions? Thanks

×