SlideShare uma empresa Scribd logo
1 de 39
Baixar para ler offline
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

Mais conteúdo relacionado

Mais procurados

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
 

Mais procurados (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
 

Destaque

[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
 

Destaque (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
 

Semelhante a 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
 

Semelhante a 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
 

Último

Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfPrecisely
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Manik S Magar
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningLars Bell
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxhariprasad279825
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clashcharlottematthew16
 
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
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionDilum Bandara
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 

Último (20)

Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine Tuning
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptx
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clash
 
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
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An Introduction
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 

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)