Introduction to Backbone.js

1,725 views

Published on

Basics of the Backbone.js framework.

Published in: Technology, Business

Introduction to Backbone.js

  1. 1. introduction & patterns Backbone.js
  2. 2. What is backbone.js A Javascript MVC framework?
  3. 3. What is backbone.js Almost.
  4. 4. What is backbone.js Collection Model View Router Sync Events S E R V E R B R O W S E R C T R L Template
  5. 5. What is backbone.js Collection Model View Router Sync Events S E R V E R B R O W S E R C T R L Template
  6. 6. Model var Todo = Backbone.Model.extend({ urlRoot: “/api/todos”, toggle: function() { this.save({done: !this.get("done")}); } }); var todo = new Todo({“id”: “1”}); todo.fetch(); todo.toggle();
  7. 7. What is backbone.js Collection Model View Router Sync Events S E R V E R B R O W S E R C T R L Template
  8. 8. Collection var Todos = Backbone.Collection.extend({ url: “/api/todos”, model: Todo, }); var todos = new Todos(); todos.fetch(); var todo = todos.get(“1”); todo.toggle();
  9. 9. What is backbone.js Collection Model View Router Sync Events S E R V E R B R O W S E R C T R L Template
  10. 10. Events var todos = new Todos(); todos.on(“change”, function(eventName, this) { console.log(“Todos changed”); }, todos); todos.fetch();
  11. 11. What is backbone.js Collection Model View Router Sync Events S E R V E R B R O W S E R C T R L Template
  12. 12. View var TodoView = Backbone.View.extend({ tagName: “li”, events: { “click .toggle”: “toggle”, }, initialize: function() { this.listenTo(this.model, “change”, this.render); }, toggle: function() { this.model.toggle(); } render: function() { this.$el.html(“<p><i class=’toggle’/>” + this.model.get(“name”) + ” </p>”); } });
  13. 13. View var TodosView = Backbone.View.extend({ initialize: function() { this.listenTo(this.collection, “change”, this.render); }, render: function() { _.each(this.collection, function(todo) { this.$el.append(new TodoView({model: todo}).render()); }); } }); var todos = new Todos(); var todosView = new TodosView({collection: todos}); todos.fetch();
  14. 14. What is backbone.js Collection Model View Router Sync Events S E R V E R B R O W S E R C T R L Template
  15. 15. Template // underscore.js ! var TodoView = Backbone.View.extend({ … template: _.template(...); render: function() { this.$el.html(this.template(this.model.attributes)); return this; } });
  16. 16. What is backbone.js Collection Model View Router Sync Events S E R V E R B R O W S E R C T R L Template
  17. 17. Router var app = Backbone.Router.extend({ routes: { “/todos”: “todos”, // #/todos “/todos/:id”: “todo” // #/todos/1 }, todos: function() { ... }, todo: function(id) { ... } });
  18. 18. This is a lot of boilerplate code.
  19. 19. Fortunately backbone.js supports inheritance!
  20. 20. Backbone patterns.
  21. 21. Thank you ● @theorm ● https://github.com/theorm/backbone-recipes

×