SlideShare a Scribd company logo
Client-side MVC with
     Backbone.js
  Jquery to Backbone.js
Agenda
•   Why Backbone.js
•   Architecture
•   Jquery to Backbone.js
•   Real World Examples
•   Resources
•   Extras
•   Questions
Why backbonejs
• From server-side to client-side
• From server-side to client-side We need
  efficient tools
• Jquery is cool but…
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);
Callback hell
jQuery 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();
        });
      });
   });
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.
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.
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
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.
Dependencies
• jQuery or Zepto
• Underscore.js
• Json2.js
MVC
•   Model / Collection
•   Template (View)
•   View (Controller)
•   Router
Model
•   Representing data (auto-generated).
•   Handling persistence.
•   Throws events.
•   Reusable.
Model
•   Fetch        HTTP GET      /url
•   Save (new)   HTTP POST     /url
•   Save         HTTP PUT      /url/id
•   Destroy      HTTP DELETE   /url/id
Model
var Item = Backbone.Model.extend({
 idAttribute: “Id”,
 urlRoot: “/Items”
});
Model
var item = new Item();
item.set({ Name: “Nick” }); // trigger change
item.save(); // trigger sync
Model
http://backbonejs.org/#Model
Collection
• A list of models.
• Underscore methods.
Collection
var Items = Backbone.Collection.extend({
  model: Item,
  url: "/Items“
});
var items = new Items();
items.fetch(); // trigger reset
items.comparator = function(item) {
  return item.get("Name");
}
Collection
http://backbonejs.org/#Collection
View
• Manipulates the DOM.
• Delegates DOM events.
• Has a Model / Collection.
Understanding backbonejs
View
var 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;
  },
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;
        }
    }
    });
});
View
var items = new Items();
var listView = new ListView({
    collection: items
});
items.fetch();
View
http://backbonejs.org/#View
Template(Underscore.js)
Compiles JavaScript templates into functions
  that can be evaluated for rendering.
• Mustache
• jQuery - tmpl
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;
    }
    …
});
Router
• Maps urls to function.
• Enable history / bookmarking.
var AppRouter = Backbone.Router.extend({
    routes: {
       "": "init"
    },
    init: function() {
       …
    }
});
Router
window.AppRouter = Backbone.Router.extend({
    routes: {
       "": "loadInvoices",
       "/add": "addInvoice",
       "/show/:id": "showInvoice",
       "/edit/:id": "editInvoice"
    },
    loadInvoices: function() {…
    },
    addInvoice: function() {…
    },
    showInvoice: function(id) {…
    },
    editInvoice: function(id) {…
    }
});
Router
http://backbonejs.org/#Router
Architecture
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('');
                }
            });
      });
});
Step to step from Jquery to
var 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('');
      }
});
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 });
});
Real World
• DocumdentCloud
• LinkedIn mobile
• Pandora
• Airbnb
• Hulu
• BaseCamp
• Diaspora
http://backbonejs.org/#examples
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/
Extra
TDD – Jasmine
http://pivotal.github.com/jasmine/

describe("Todo", function() {
    it("Should have a title", function() {
        var todo = new Todo();
        expect(todo.get("title")).toBeDefined();
    });
});
Pros and Cons
+
•   Lightweight
•   Powerful
•   Code is clean(and maintainable)
-
•   Too verbose(for small applications)
Questions?
  Thanks

More Related Content

PPT
BackboneJs
PPTX
Backbonejs for beginners
PPTX
BackboneJS Training - Giving Backbone to your applications
PDF
Backbone js in action
PDF
Backbone
KEY
【前端Mvc】之豆瓣说实践
PDF
Intro to BackboneJS + Intermediate Javascript
ODP
BackboneJS and friends
BackboneJs
Backbonejs for beginners
BackboneJS Training - Giving Backbone to your applications
Backbone js in action
Backbone
【前端Mvc】之豆瓣说实践
Intro to BackboneJS + Intermediate Javascript
BackboneJS and friends

What's hot (20)

PPTX
Planbox Backbone MVC
PDF
Viking academy backbone.js
PPT
Backbone js
PPTX
AngularJS - $http & $resource Services
PPTX
Javascript first-class citizenery
PPTX
Taming that client side mess with Backbone.js
PDF
Drupal 8: Fields reborn
PDF
Upgrade your javascript to drupal 8
PPTX
AngularJS Directives
PPTX
AngularJS Services
PDF
Introduction to Backbone.js for Rails developers
PPTX
AngularJS Compile Process
PDF
In-depth changes to Drupal 8 javascript
PPTX
AngularJS Routing
PDF
Cassandra java libraries
PDF
[Srijan Wednesday Webinars] Ruling Drupal 8 with #d8rules
PDF
Effective cassandra development with achilles
PDF
Backbone.js — Introduction to client-side JavaScript MVC
PPTX
Practical AngularJS
PDF
Angular js routing options
Planbox Backbone MVC
Viking academy backbone.js
Backbone js
AngularJS - $http & $resource Services
Javascript first-class citizenery
Taming that client side mess with Backbone.js
Drupal 8: Fields reborn
Upgrade your javascript to drupal 8
AngularJS Directives
AngularJS Services
Introduction to Backbone.js for Rails developers
AngularJS Compile Process
In-depth changes to Drupal 8 javascript
AngularJS Routing
Cassandra java libraries
[Srijan Wednesday Webinars] Ruling Drupal 8 with #d8rules
Effective cassandra development with achilles
Backbone.js — Introduction to client-side JavaScript MVC
Practical AngularJS
Angular js routing options
Ad

Viewers also liked (6)

PDF
[XECon2016] A-3 박형식 Frontend stack의 변화 : jQuery, BackboneJS, ReactJS 중심으로
PDF
Backbonejs Full Stack
PDF
Drupal8 + AngularJS
PPTX
Top 5 Javascript Frameworks for Web and Mobile App Development
PDF
JS Framework Comparison - An infographic
PPTX
Single Page Applications with AngularJS 2.0
[XECon2016] A-3 박형식 Frontend stack의 변화 : jQuery, BackboneJS, ReactJS 중심으로
Backbonejs Full Stack
Drupal8 + AngularJS
Top 5 Javascript Frameworks for Web and Mobile App Development
JS Framework Comparison - An infographic
Single Page Applications with AngularJS 2.0
Ad

Similar to Understanding backbonejs (20)

PPT
Backbone.js
PDF
Backbone.js
PPTX
Backbone.js
PDF
Backbone js
KEY
Backbone.js Simple Tutorial
PDF
Javascript Application Architecture with Backbone.JS
PDF
Raybiztech Guide To Backbone Javascript Library
PPT
Backbone js
PDF
Backbone Basics with Examples
PDF
Javascript MVC & Backbone Tips & Tricks
PDF
Backbone.js
PPTX
Backbone the Good Parts
KEY
Single Page Web Apps with Backbone.js and Rails
KEY
Prateek dayal backbonerails-110528024926-phpapp02
PDF
[2015/2016] Backbone JS
ODP
Javascript frameworks: Backbone.js
KEY
Backbone.js
PDF
Backbone.js
PDF
Backbone beyond jQuery
PPTX
Creating Single Page Web App using Backbone JS
Backbone.js
Backbone.js
Backbone.js
Backbone js
Backbone.js Simple Tutorial
Javascript Application Architecture with Backbone.JS
Raybiztech Guide To Backbone Javascript Library
Backbone js
Backbone Basics with Examples
Javascript MVC & Backbone Tips & Tricks
Backbone.js
Backbone the Good Parts
Single Page Web Apps with Backbone.js and Rails
Prateek dayal backbonerails-110528024926-phpapp02
[2015/2016] Backbone JS
Javascript frameworks: Backbone.js
Backbone.js
Backbone.js
Backbone beyond jQuery
Creating Single Page Web App using Backbone JS

Recently uploaded (20)

PPTX
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
PDF
Advanced Soft Computing BINUS July 2025.pdf
PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
PDF
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
PDF
CIFDAQ's Market Insight: SEC Turns Pro Crypto
PDF
Network Security Unit 5.pdf for BCA BBA.
PDF
Approach and Philosophy of On baking technology
PDF
Unlocking AI with Model Context Protocol (MCP)
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PDF
Electronic commerce courselecture one. Pdf
PDF
solutions_manual_-_materials___processing_in_manufacturing__demargo_.pdf
PDF
GDG Cloud Iasi [PUBLIC] Florian Blaga - Unveiling the Evolution of Cybersecur...
PPTX
breach-and-attack-simulation-cybersecurity-india-chennai-defenderrabbit-2025....
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
PDF
GamePlan Trading System Review: Professional Trader's Honest Take
PDF
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
PDF
Modernizing your data center with Dell and AMD
PPTX
Understanding_Digital_Forensics_Presentation.pptx
PDF
NewMind AI Monthly Chronicles - July 2025
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
Advanced Soft Computing BINUS July 2025.pdf
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
CIFDAQ's Market Insight: SEC Turns Pro Crypto
Network Security Unit 5.pdf for BCA BBA.
Approach and Philosophy of On baking technology
Unlocking AI with Model Context Protocol (MCP)
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
Electronic commerce courselecture one. Pdf
solutions_manual_-_materials___processing_in_manufacturing__demargo_.pdf
GDG Cloud Iasi [PUBLIC] Florian Blaga - Unveiling the Evolution of Cybersecur...
breach-and-attack-simulation-cybersecurity-india-chennai-defenderrabbit-2025....
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
“AI and Expert System Decision Support & Business Intelligence Systems”
GamePlan Trading System Review: Professional Trader's Honest Take
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
Modernizing your data center with Dell and AMD
Understanding_Digital_Forensics_Presentation.pptx
NewMind AI Monthly Chronicles - July 2025

Understanding backbonejs

  • 1. Client-side MVC with Backbone.js Jquery to Backbone.js
  • 2. Agenda • Why Backbone.js • Architecture • Jquery to Backbone.js • Real World Examples • Resources • Extras • Questions
  • 3. Why backbonejs • From server-side to client-side • From server-side to client-side We need efficient tools • Jquery is cool but…
  • 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. Callback hell jQuery 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. 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. 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. 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. 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. Dependencies • jQuery or Zepto • Underscore.js • Json2.js
  • 11. MVC • Model / Collection • Template (View) • View (Controller) • Router
  • 12. Model • Representing data (auto-generated). • Handling persistence. • Throws events. • Reusable.
  • 13. Model • Fetch HTTP GET /url • Save (new) HTTP POST /url • Save HTTP PUT /url/id • Destroy HTTP DELETE /url/id
  • 14. Model var Item = Backbone.Model.extend({ idAttribute: “Id”, urlRoot: “/Items” });
  • 15. Model var item = new Item(); item.set({ Name: “Nick” }); // trigger change item.save(); // trigger sync
  • 17. Collection • A list of models. • Underscore methods.
  • 18. Collection var Items = Backbone.Collection.extend({ model: Item, url: "/Items“ }); var items = new Items(); items.fetch(); // trigger reset items.comparator = function(item) { return item.get("Name"); }
  • 20. View • Manipulates the DOM. • Delegates DOM events. • Has a Model / Collection.
  • 22. View var 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; },
  • 23. 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; } } }); });
  • 24. View var items = new Items(); var listView = new ListView({ collection: items }); items.fetch();
  • 26. Template(Underscore.js) Compiles JavaScript templates into functions that can be evaluated for rendering. • Mustache • jQuery - tmpl
  • 27. 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; } … });
  • 28. Router • Maps urls to function. • Enable history / bookmarking. var AppRouter = Backbone.Router.extend({ routes: { "": "init" }, init: function() { … } });
  • 29. Router window.AppRouter = Backbone.Router.extend({ routes: { "": "loadInvoices", "/add": "addInvoice", "/show/:id": "showInvoice", "/edit/:id": "editInvoice" }, loadInvoices: function() {… }, addInvoice: function() {… }, showInvoice: function(id) {… }, editInvoice: function(id) {… } });
  • 32. 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(''); } }); }); });
  • 33. Step to step from Jquery to var 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(''); } });
  • 34. 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 }); });
  • 35. Real World • DocumdentCloud • LinkedIn mobile • Pandora • Airbnb • Hulu • BaseCamp • Diaspora http://backbonejs.org/#examples
  • 36. 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/
  • 37. Extra TDD – Jasmine http://pivotal.github.com/jasmine/ describe("Todo", function() { it("Should have a title", function() { var todo = new Todo(); expect(todo.get("title")).toBeDefined(); }); });
  • 38. Pros and Cons + • Lightweight • Powerful • Code is clean(and maintainable) - • Too verbose(for small applications)