SlideShare ist ein Scribd-Unternehmen logo
1 von 39
Downloaden Sie, um offline zu lesen
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.
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

Weitere ähnliche Inhalte

Was ist angesagt?

Planbox Backbone MVC
Planbox Backbone MVCPlanbox Backbone MVC
Planbox Backbone MVCAcquisio
 
Viking academy backbone.js
Viking academy  backbone.jsViking academy  backbone.js
Viking academy backbone.jsBert Wijnants
 
AngularJS - $http & $resource Services
AngularJS - $http & $resource ServicesAngularJS - $http & $resource Services
AngularJS - $http & $resource ServicesEyal Vardi
 
Javascript first-class citizenery
Javascript first-class citizeneryJavascript first-class citizenery
Javascript first-class citizenerytoddbr
 
Taming that client side mess with Backbone.js
Taming that client side mess with Backbone.jsTaming that client side mess with Backbone.js
Taming that client side mess with Backbone.jsJarod Ferguson
 
Upgrade your javascript to drupal 8
Upgrade your javascript to drupal 8Upgrade your javascript to drupal 8
Upgrade your javascript to drupal 8Théodore Biadala
 
AngularJS Directives
AngularJS DirectivesAngularJS Directives
AngularJS DirectivesEyal Vardi
 
AngularJS Services
AngularJS ServicesAngularJS Services
AngularJS ServicesEyal Vardi
 
Introduction to Backbone.js for Rails developers
Introduction to Backbone.js for Rails developersIntroduction to Backbone.js for Rails developers
Introduction to Backbone.js for Rails developersAoteaStudios
 
AngularJS Compile Process
AngularJS Compile ProcessAngularJS Compile Process
AngularJS Compile ProcessEyal Vardi
 
In-depth changes to Drupal 8 javascript
In-depth changes to Drupal 8 javascriptIn-depth changes to Drupal 8 javascript
In-depth changes to Drupal 8 javascriptThéodore Biadala
 
AngularJS Routing
AngularJS RoutingAngularJS Routing
AngularJS RoutingEyal Vardi
 
Cassandra java libraries
Cassandra java librariesCassandra java libraries
Cassandra java librariesDuyhai Doan
 
[Srijan Wednesday Webinars] Ruling Drupal 8 with #d8rules
[Srijan Wednesday Webinars] Ruling Drupal 8 with #d8rules[Srijan Wednesday Webinars] Ruling Drupal 8 with #d8rules
[Srijan Wednesday Webinars] Ruling Drupal 8 with #d8rulesSrijan Technologies
 
Effective cassandra development with achilles
Effective cassandra development with achillesEffective cassandra development with achilles
Effective cassandra development with achillesDuyhai Doan
 
Backbone.js — Introduction to client-side JavaScript MVC
Backbone.js — Introduction to client-side JavaScript MVCBackbone.js — Introduction to client-side JavaScript MVC
Backbone.js — Introduction to client-side JavaScript MVCpootsbook
 
Practical AngularJS
Practical AngularJSPractical AngularJS
Practical AngularJSWei Ru
 
Angular js routing options
Angular js routing optionsAngular js routing options
Angular js routing optionsNir Kaufman
 

Was ist angesagt? (20)

Planbox Backbone MVC
Planbox Backbone MVCPlanbox Backbone MVC
Planbox Backbone MVC
 
Viking academy backbone.js
Viking academy  backbone.jsViking academy  backbone.js
Viking academy backbone.js
 
Backbone js
Backbone jsBackbone js
Backbone js
 
AngularJS - $http & $resource Services
AngularJS - $http & $resource ServicesAngularJS - $http & $resource Services
AngularJS - $http & $resource Services
 
Javascript first-class citizenery
Javascript first-class citizeneryJavascript first-class citizenery
Javascript first-class citizenery
 
Taming that client side mess with Backbone.js
Taming that client side mess with Backbone.jsTaming that client side mess with Backbone.js
Taming that client side mess with Backbone.js
 
Drupal 8: Fields reborn
Drupal 8: Fields rebornDrupal 8: Fields reborn
Drupal 8: Fields reborn
 
Upgrade your javascript to drupal 8
Upgrade your javascript to drupal 8Upgrade your javascript to drupal 8
Upgrade your javascript to drupal 8
 
AngularJS Directives
AngularJS DirectivesAngularJS Directives
AngularJS Directives
 
AngularJS Services
AngularJS ServicesAngularJS Services
AngularJS Services
 
Introduction to Backbone.js for Rails developers
Introduction to Backbone.js for Rails developersIntroduction to Backbone.js for Rails developers
Introduction to Backbone.js for Rails developers
 
AngularJS Compile Process
AngularJS Compile ProcessAngularJS Compile Process
AngularJS Compile Process
 
In-depth changes to Drupal 8 javascript
In-depth changes to Drupal 8 javascriptIn-depth changes to Drupal 8 javascript
In-depth changes to Drupal 8 javascript
 
AngularJS Routing
AngularJS RoutingAngularJS Routing
AngularJS Routing
 
Cassandra java libraries
Cassandra java librariesCassandra java libraries
Cassandra java libraries
 
[Srijan Wednesday Webinars] Ruling Drupal 8 with #d8rules
[Srijan Wednesday Webinars] Ruling Drupal 8 with #d8rules[Srijan Wednesday Webinars] Ruling Drupal 8 with #d8rules
[Srijan Wednesday Webinars] Ruling Drupal 8 with #d8rules
 
Effective cassandra development with achilles
Effective cassandra development with achillesEffective cassandra development with achilles
Effective cassandra development with achilles
 
Backbone.js — Introduction to client-side JavaScript MVC
Backbone.js — Introduction to client-side JavaScript MVCBackbone.js — Introduction to client-side JavaScript MVC
Backbone.js — Introduction to client-side JavaScript MVC
 
Practical AngularJS
Practical AngularJSPractical AngularJS
Practical AngularJS
 
Angular js routing options
Angular js routing optionsAngular js routing options
Angular js routing options
 

Andere mochten auch

[XECon2016] A-3 박형식 Frontend stack의 변화 : jQuery, BackboneJS, ReactJS 중심으로
[XECon2016] A-3 박형식 Frontend stack의 변화 : jQuery, BackboneJS, ReactJS 중심으로[XECon2016] A-3 박형식 Frontend stack의 변화 : jQuery, BackboneJS, ReactJS 중심으로
[XECon2016] A-3 박형식 Frontend stack의 변화 : jQuery, BackboneJS, ReactJS 중심으로XpressEngine
 
Top 5 Javascript Frameworks for Web and Mobile App Development
Top 5 Javascript Frameworks for Web and Mobile App DevelopmentTop 5 Javascript Frameworks for Web and Mobile App Development
Top 5 Javascript Frameworks for Web and Mobile App DevelopmentAjeet Singh
 
JS Framework Comparison - An infographic
JS Framework Comparison - An infographicJS Framework Comparison - An infographic
JS Framework Comparison - An infographicInApp
 
Single Page Applications with AngularJS 2.0
Single Page Applications with AngularJS 2.0 Single Page Applications with AngularJS 2.0
Single Page Applications with AngularJS 2.0 Sumanth Chinthagunta
 

Andere mochten auch (6)

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

Ähnlich wie Client-side MVC with Backbone.js: Jquery to Backbone.js

Aplicacoes dinamicas Rails com Backbone
Aplicacoes dinamicas Rails com BackboneAplicacoes dinamicas Rails com Backbone
Aplicacoes dinamicas Rails com BackboneRafael Felix da Silva
 
Backbone.js Simple Tutorial
Backbone.js Simple TutorialBackbone.js Simple Tutorial
Backbone.js Simple Tutorial추근 문
 
前端MVC 豆瓣说
前端MVC 豆瓣说前端MVC 豆瓣说
前端MVC 豆瓣说Ting Lv
 
前端MVC之BackboneJS
前端MVC之BackboneJS前端MVC之BackboneJS
前端MVC之BackboneJSZhang Xiaoxue
 
Prateek dayal backbonerails-110528024926-phpapp02
Prateek dayal backbonerails-110528024926-phpapp02Prateek dayal backbonerails-110528024926-phpapp02
Prateek dayal backbonerails-110528024926-phpapp02Revath S Kumar
 
Single Page Web Apps with Backbone.js and Rails
Single Page Web Apps with Backbone.js and RailsSingle Page Web Apps with Backbone.js and Rails
Single Page Web Apps with Backbone.js and RailsPrateek Dayal
 
Javascript MVC & Backbone Tips & Tricks
Javascript MVC & Backbone Tips & TricksJavascript MVC & Backbone Tips & Tricks
Javascript MVC & Backbone Tips & TricksHjörtur Hilmarsson
 
Doctrine For Beginners
Doctrine For BeginnersDoctrine For Beginners
Doctrine For BeginnersJonathan Wage
 
Using Backbone.js with Drupal 7 and 8
Using Backbone.js with Drupal 7 and 8Using Backbone.js with Drupal 7 and 8
Using Backbone.js with Drupal 7 and 8Ovadiah Myrgorod
 
Building Lithium Apps
Building Lithium AppsBuilding Lithium Apps
Building Lithium AppsNate Abele
 
Writing HTML5 Web Apps using Backbone.js and GAE
Writing HTML5 Web Apps using Backbone.js and GAEWriting HTML5 Web Apps using Backbone.js and GAE
Writing HTML5 Web Apps using Backbone.js and GAERon Reiter
 
jQuery and Rails: Best Friends Forever
jQuery and Rails: Best Friends ForeverjQuery and Rails: Best Friends Forever
jQuery and Rails: Best Friends Foreverstephskardal
 
Javascript Application Architecture with Backbone.JS
Javascript Application Architecture with Backbone.JSJavascript Application Architecture with Backbone.JS
Javascript Application Architecture with Backbone.JSMin Ming Lo
 
Lift 2 0
Lift 2 0Lift 2 0
Lift 2 0SO
 

Ähnlich wie Client-side MVC with Backbone.js: Jquery to Backbone.js (20)

Aplicacoes dinamicas Rails com Backbone
Aplicacoes dinamicas Rails com BackboneAplicacoes dinamicas Rails com Backbone
Aplicacoes dinamicas Rails com Backbone
 
Backbone.js Simple Tutorial
Backbone.js Simple TutorialBackbone.js Simple Tutorial
Backbone.js Simple Tutorial
 
前端MVC 豆瓣说
前端MVC 豆瓣说前端MVC 豆瓣说
前端MVC 豆瓣说
 
前端MVC之BackboneJS
前端MVC之BackboneJS前端MVC之BackboneJS
前端MVC之BackboneJS
 
Prateek dayal backbonerails-110528024926-phpapp02
Prateek dayal backbonerails-110528024926-phpapp02Prateek dayal backbonerails-110528024926-phpapp02
Prateek dayal backbonerails-110528024926-phpapp02
 
Single Page Web Apps with Backbone.js and Rails
Single Page Web Apps with Backbone.js and RailsSingle Page Web Apps with Backbone.js and Rails
Single Page Web Apps with Backbone.js and Rails
 
Javascript MVC & Backbone Tips & Tricks
Javascript MVC & Backbone Tips & TricksJavascript MVC & Backbone Tips & Tricks
Javascript MVC & Backbone Tips & Tricks
 
Backbone.js
Backbone.jsBackbone.js
Backbone.js
 
Doctrine For Beginners
Doctrine For BeginnersDoctrine For Beginners
Doctrine For Beginners
 
Using Backbone.js with Drupal 7 and 8
Using Backbone.js with Drupal 7 and 8Using Backbone.js with Drupal 7 and 8
Using Backbone.js with Drupal 7 and 8
 
Backbone js-slides
Backbone js-slidesBackbone js-slides
Backbone js-slides
 
Building Lithium Apps
Building Lithium AppsBuilding Lithium Apps
Building Lithium Apps
 
jQuery
jQueryjQuery
jQuery
 
Min-Maxing Software Costs
Min-Maxing Software CostsMin-Maxing Software Costs
Min-Maxing Software Costs
 
Writing HTML5 Web Apps using Backbone.js and GAE
Writing HTML5 Web Apps using Backbone.js and GAEWriting HTML5 Web Apps using Backbone.js and GAE
Writing HTML5 Web Apps using Backbone.js and GAE
 
jQuery
jQueryjQuery
jQuery
 
Rails is not just Ruby
Rails is not just RubyRails is not just Ruby
Rails is not just Ruby
 
jQuery and Rails: Best Friends Forever
jQuery and Rails: Best Friends ForeverjQuery and Rails: Best Friends Forever
jQuery and Rails: Best Friends Forever
 
Javascript Application Architecture with Backbone.JS
Javascript Application Architecture with Backbone.JSJavascript Application Architecture with Backbone.JS
Javascript Application Architecture with Backbone.JS
 
Lift 2 0
Lift 2 0Lift 2 0
Lift 2 0
 

Kürzlich hochgeladen

Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better StrongerModern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better Strongerpanagenda
 
Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Hiroshi SHIBATA
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxLoriGlavin3
 
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...panagenda
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersRaghuram Pandurangan
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxLoriGlavin3
 
Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rick Flair
 
Scale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterScale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterMydbops
 
Assure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyesAssure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyesThousandEyes
 
Generative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfGenerative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfIngrid Airi González
 
UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPathCommunity
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfLoriGlavin3
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesThousandEyes
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
Potential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsPotential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsRavi Sanghani
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxLoriGlavin3
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxLoriGlavin3
 
Decarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityDecarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityIES VE
 
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Mark Goldstein
 

Kürzlich hochgeladen (20)

Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better StrongerModern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
 
Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
 
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information Developers
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
 
Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...
 
Scale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterScale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL Router
 
Assure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyesAssure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyes
 
Generative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfGenerative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdf
 
UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to Hero
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdf
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
Potential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsPotential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and Insights
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
 
Decarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityDecarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a reality
 
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
 

Client-side MVC with Backbone.js: Jquery to Backbone.js

  • 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.
  • 21.
  • 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)