SlideShare ist ein Scribd-Unternehmen logo
1 von 36
get a backbone
an intro to the javascript mvc framework
outline
• why you need an mvc framework
• what backbone is
• how we use it in workday
catopia
the webapp
persist on server,
          access via restful api

               RESTful request
serv er
                  response
/rest/kittens
json object
  {
          “kittens”:
          [
          {
             “id”: “1”,
             “name”: “Max”,
             "plaything": "catnip"
          },
          {
             “id”: “2”,
             "name": "Orhan",
             "plaything": "sofa legs"
          }
      ]
  }
$.ajax({
   url: '/rest/kittens'
   success: function(response) {

          _.each(response.kittens, function(kitten) {

               var kittenTemplate = ...//some template

               // Go make all the table rows.
               $("#cat-container").append(kittenTemplate);

          })

      }
});
catopia
 max     catnip
orhan   sofa legs
catopia
max      catnip
orhan   sofa legs
<tr class=”kitten-row” kitten-id=”1”>
  <td class=”kitten-photo”><img src=”max.jpg”></td>
  <td class=”kitten-name”>max</td>
  <td class=”kitten-plaything”>catnip</td>
  <td class=”kitten-delete”><img src=”delete.jpg”></td>
</tr>


                   max       catnip
<tr class=”kitten-row” kitten-id=”1”>
  <td class=”kitten-photo”><img src=”max.jpg”></td>
  <td class=”kitten-name”>max</td>
  <td class=”kitten-plaything”>catnip</td>
  <td class=”kitten-delete”><img src=”delete.jpg”></td>
</tr>


                   max       catnip
max        catnip

$(“.kitten-delete”).click(function () {

 // Find the ID of the kitten
 var id = $(this).closest(“.kitten-row”).attr(“kitten-id”);

 // Do the delete request
 $.ajax(
   url: “/rest/kittens/1”,
   type: “DELETE”
 });
max        catnip

$(“.kitten-delete”).click(function () {

 // Find the ID of the kitten
 var kittenRow = $(this).closest(“.kitten-row”);
 var id = kittenRow.attr(“kitten-id”);

 // Do the delete request
 $.ajax(
   url: “/rest/kittens/1”,
   type: “DELETE”,
   success: function () {
     kittenRow.remove();
     }
 });
i haz a sad




my data is tightly coupled to my DOM
just imagine
if my data wasn’t
coupled to the DOM?
if my kittens could
update themselves!
javascript mvc
  frameworks
      backbone.js
      spine.js
      javascriptMVC
       is different to

cappucino
sencha
                           widgets
sproutcore
                         UI elements
backbone.js
lightweight ~4kb
one hard dependency: underscore.js
compatible with jQuery or Zepto
used by foursquare, trello, khan academy
models
collections
  views
models
              where we keep our data
                + utility functions


// Create a Kitten model by extending Backbone.Model
var Kitten = Backbone.Model.extend({
    // something we want all kittens to do
    play: function () {
        console.log("Playing with " + this.model.get("plaything"));
    }
}
models
instantiating a model




var max = new Kitten();
max.play();
models
                access data via set and get
                 can validate data easily
// Create a Kitten model by extending Backbone.Model
var Kitten = Backbone.Model.extend({

    // validate our data by overriding the method
    // in Backbone.Model
    validate: function(attrs) {
      if (attrs.plaything == “dog”) {
         // error
         return “You haven’t watched enough Hanna-Barbera cartoons.”
      }
    }
}

// Instantiate a kitten.
var max = new Kitten();
max.set({plaything: "twine"});
collections
              arrays of model instances

// Create a collection of kittens!
var Kittens = Backbone.Collection.extend({
    model: Kitten // default model
}


var kittens = new Kittens;
kittens.add({name: “Max”});         whenever you add a new item,
kittens.add({name: “Orhan”});       an add event is fired. useful!

                                    e.g.
                                    kittens.bind(add, function(kitten) {
                                      alert(“Hi “ + kitten.get(“name”));
                                      }
collections
                populating collections

var Kittens = Backbone.Collection.extend({
    model: Kitten
    url: ‘/rest/kittens’
}


var kittens = new Kittens;
kittens.fetch();
collections
               syncing with the server

var Kittens = Backbone.Collection.extend({
    model: Kitten
    url: ‘/rest/kittens’
}


var kittens = new Kittens;
kittens.fetch();
models
          syncing with the server

var Kitten = Backbone.Model.extend({
    url: ‘/rest/kittens’
}
collections
                  backbone.sync


The default sync handler maps CRUD to REST like so:

 ◦ create → POST   /collection
 ◦ read → GET   /collection[/id]
 ◦ update → PUT   /collection/id
 ◦ delete → DELETE   /collection/id
each model has an associated view

         max has a
         model
         view
                              both models are in a
                                Kittens collection
                       (they could be in others too! like a
                       CuteThings collection. doesn’t have
         orhan has a          to be a 1-1 mapping)

         model
         view
views
          let’s create views for our kittens
// Getting Max out of our kitten collection, he had an ID of 1
var max = kittens.get(1);

// We’ll look at the view in detail next
new KittenView({model: max});
views

var KittenView = Backbone.View.extend({
  tagName: “tr”,
  className: “kitten-row”,
  template: _.template($(“#kitten-template”).html()),

  render: function() {
    $(this.el).html(this.template(this.model.toJSON())));
    return this;
  }
});
                         this will return some HTML
   all views have an
  associated element
views
          let’s do some add in that feature
var KittenView = Backbone.View.extend({
  tagName: “tr”,
  className: “kitten-row”,
  template: _.template($(“#kitten-template”).html()),

  events: {
    “keypress .delete-icon”: “destroyKitten”
  }

  destroyKitten: function() {
    this.model.destroy();
  }

  render: function() {
    $(this.el).html(this.template(this.model.toJSON())));
    return this;
  }
});
workday
models          views
notifications    notification view
starred items   starred item view

collections
notifications       appview
starred items
moar
backbone.js & underscore.js docs
backbone demo: todos // small well-commented app
javascript web applications // an o’reilly book

Weitere ähnliche Inhalte

Was ist angesagt?

Eddystone Beacons - Physical Web - Giving a URL to All Objects
Eddystone Beacons - Physical Web - Giving a URL to All ObjectsEddystone Beacons - Physical Web - Giving a URL to All Objects
Eddystone Beacons - Physical Web - Giving a URL to All ObjectsJeff Prestes
 
Beacons, Raspberry Pi & Node.js
Beacons, Raspberry Pi & Node.jsBeacons, Raspberry Pi & Node.js
Beacons, Raspberry Pi & Node.jsJeff Prestes
 
Elasticsearch sur Azure : Make sense of your (BIG) data !
Elasticsearch sur Azure : Make sense of your (BIG) data !Elasticsearch sur Azure : Make sense of your (BIG) data !
Elasticsearch sur Azure : Make sense of your (BIG) data !Microsoft
 
What Would You Do? With John Quinones
What Would You Do? With John QuinonesWhat Would You Do? With John Quinones
What Would You Do? With John Quinonesalertchair8725
 
FrontendLab: Programming UI with FRP and Bacon js - Вячеслав Ворончук
FrontendLab: Programming UI with FRP and Bacon js - Вячеслав ВорончукFrontendLab: Programming UI with FRP and Bacon js - Вячеслав Ворончук
FrontendLab: Programming UI with FRP and Bacon js - Вячеслав ВорончукGeeksLab Odessa
 
node.js Module Development
node.js Module Developmentnode.js Module Development
node.js Module DevelopmentJay Harris
 
Why (I think) CoffeeScript Is Awesome
Why (I think) CoffeeScript Is AwesomeWhy (I think) CoffeeScript Is Awesome
Why (I think) CoffeeScript Is AwesomeJo Cranford
 
201204 random clustering
201204 random clustering201204 random clustering
201204 random clusteringpluskjw
 
International News | World News
International News | World NewsInternational News | World News
International News | World Newsproductiveengin27
 
FRP and Bacon.js
FRP and Bacon.jsFRP and Bacon.js
FRP and Bacon.jsStarbuildr
 
[Hatsune Miku] Shoot Frieza with Amazon Kinesis ! [EN]
[Hatsune Miku] Shoot Frieza with Amazon Kinesis ! [EN][Hatsune Miku] Shoot Frieza with Amazon Kinesis ! [EN]
[Hatsune Miku] Shoot Frieza with Amazon Kinesis ! [EN]崇之 清水
 
Programmers, communicate your intentions
Programmers, communicate your intentionsProgrammers, communicate your intentions
Programmers, communicate your intentionsYael Zaritsky Perez
 
Mongoose and MongoDB 101
Mongoose and MongoDB 101Mongoose and MongoDB 101
Mongoose and MongoDB 101Will Button
 

Was ist angesagt? (20)

Eddystone Beacons - Physical Web - Giving a URL to All Objects
Eddystone Beacons - Physical Web - Giving a URL to All ObjectsEddystone Beacons - Physical Web - Giving a URL to All Objects
Eddystone Beacons - Physical Web - Giving a URL to All Objects
 
Attribute
AttributeAttribute
Attribute
 
Beacons, Raspberry Pi & Node.js
Beacons, Raspberry Pi & Node.jsBeacons, Raspberry Pi & Node.js
Beacons, Raspberry Pi & Node.js
 
Elasticsearch sur Azure : Make sense of your (BIG) data !
Elasticsearch sur Azure : Make sense of your (BIG) data !Elasticsearch sur Azure : Make sense of your (BIG) data !
Elasticsearch sur Azure : Make sense of your (BIG) data !
 
What Would You Do? With John Quinones
What Would You Do? With John QuinonesWhat Would You Do? With John Quinones
What Would You Do? With John Quinones
 
FrontendLab: Programming UI with FRP and Bacon js - Вячеслав Ворончук
FrontendLab: Programming UI with FRP and Bacon js - Вячеслав ВорончукFrontendLab: Programming UI with FRP and Bacon js - Вячеслав Ворончук
FrontendLab: Programming UI with FRP and Bacon js - Вячеслав Ворончук
 
node.js Module Development
node.js Module Developmentnode.js Module Development
node.js Module Development
 
Why (I think) CoffeeScript Is Awesome
Why (I think) CoffeeScript Is AwesomeWhy (I think) CoffeeScript Is Awesome
Why (I think) CoffeeScript Is Awesome
 
Kotlin Generation
Kotlin GenerationKotlin Generation
Kotlin Generation
 
Chapter 4
Chapter 4Chapter 4
Chapter 4
 
201204 random clustering
201204 random clustering201204 random clustering
201204 random clustering
 
Prototype UI Intro
Prototype UI IntroPrototype UI Intro
Prototype UI Intro
 
Epic South Disasters
Epic South DisastersEpic South Disasters
Epic South Disasters
 
International News | World News
International News | World NewsInternational News | World News
International News | World News
 
FRP and Bacon.js
FRP and Bacon.jsFRP and Bacon.js
FRP and Bacon.js
 
[Hatsune Miku] Shoot Frieza with Amazon Kinesis ! [EN]
[Hatsune Miku] Shoot Frieza with Amazon Kinesis ! [EN][Hatsune Miku] Shoot Frieza with Amazon Kinesis ! [EN]
[Hatsune Miku] Shoot Frieza with Amazon Kinesis ! [EN]
 
Nubilus Perl
Nubilus PerlNubilus Perl
Nubilus Perl
 
Programmers, communicate your intentions
Programmers, communicate your intentionsProgrammers, communicate your intentions
Programmers, communicate your intentions
 
Say It With Javascript
Say It With JavascriptSay It With Javascript
Say It With Javascript
 
Mongoose and MongoDB 101
Mongoose and MongoDB 101Mongoose and MongoDB 101
Mongoose and MongoDB 101
 

Andere mochten auch

Your Brain on Code
Your Brain on CodeYour Brain on Code
Your Brain on Codenabeelahali
 
Remixing Confluence With Speakeasy
Remixing Confluence With SpeakeasyRemixing Confluence With Speakeasy
Remixing Confluence With Speakeasynabeelahali
 
Arduino JumpStart
Arduino JumpStartArduino JumpStart
Arduino JumpStartnabeelahali
 
How to Teach Your Grandmother
How to Teach Your GrandmotherHow to Teach Your Grandmother
How to Teach Your Grandmothernabeelahali
 
Contribuição sobre movimentação financeira (cpmf)
Contribuição sobre movimentação financeira (cpmf)Contribuição sobre movimentação financeira (cpmf)
Contribuição sobre movimentação financeira (cpmf)razonetecontabil
 
Veja as fotos comentadas...
Veja as fotos comentadas...Veja as fotos comentadas...
Veja as fotos comentadas...Alunos
 
Recursos Naturales de Chile
 Recursos Naturales de Chile Recursos Naturales de Chile
Recursos Naturales de ChileCristy G
 
Activate Tech and Media Outlook 2017
Activate Tech and Media Outlook 2017Activate Tech and Media Outlook 2017
Activate Tech and Media Outlook 2017Activate
 
Study: The Future of VR, AR and Self-Driving Cars
Study: The Future of VR, AR and Self-Driving CarsStudy: The Future of VR, AR and Self-Driving Cars
Study: The Future of VR, AR and Self-Driving CarsLinkedIn
 
Hype vs. Reality: The AI Explainer
Hype vs. Reality: The AI ExplainerHype vs. Reality: The AI Explainer
Hype vs. Reality: The AI ExplainerLuminary Labs
 

Andere mochten auch (10)

Your Brain on Code
Your Brain on CodeYour Brain on Code
Your Brain on Code
 
Remixing Confluence With Speakeasy
Remixing Confluence With SpeakeasyRemixing Confluence With Speakeasy
Remixing Confluence With Speakeasy
 
Arduino JumpStart
Arduino JumpStartArduino JumpStart
Arduino JumpStart
 
How to Teach Your Grandmother
How to Teach Your GrandmotherHow to Teach Your Grandmother
How to Teach Your Grandmother
 
Contribuição sobre movimentação financeira (cpmf)
Contribuição sobre movimentação financeira (cpmf)Contribuição sobre movimentação financeira (cpmf)
Contribuição sobre movimentação financeira (cpmf)
 
Veja as fotos comentadas...
Veja as fotos comentadas...Veja as fotos comentadas...
Veja as fotos comentadas...
 
Recursos Naturales de Chile
 Recursos Naturales de Chile Recursos Naturales de Chile
Recursos Naturales de Chile
 
Activate Tech and Media Outlook 2017
Activate Tech and Media Outlook 2017Activate Tech and Media Outlook 2017
Activate Tech and Media Outlook 2017
 
Study: The Future of VR, AR and Self-Driving Cars
Study: The Future of VR, AR and Self-Driving CarsStudy: The Future of VR, AR and Self-Driving Cars
Study: The Future of VR, AR and Self-Driving Cars
 
Hype vs. Reality: The AI Explainer
Hype vs. Reality: The AI ExplainerHype vs. Reality: The AI Explainer
Hype vs. Reality: The AI Explainer
 

Ähnlich wie Backbone intro

Introducing CakeEntity
Introducing CakeEntityIntroducing CakeEntity
Introducing CakeEntityBasuke Suzuki
 
Art of Javascript
Art of JavascriptArt of Javascript
Art of JavascriptTarek Yehia
 
Object-Oriented Javascript
Object-Oriented JavascriptObject-Oriented Javascript
Object-Oriented Javascriptkvangork
 
Object-Oriented JavaScript
Object-Oriented JavaScriptObject-Oriented JavaScript
Object-Oriented JavaScriptkvangork
 
前端MVC 豆瓣说
前端MVC 豆瓣说前端MVC 豆瓣说
前端MVC 豆瓣说Ting Lv
 
Secrets of JavaScript Libraries
Secrets of JavaScript LibrariesSecrets of JavaScript Libraries
Secrets of JavaScript Librariesjeresig
 
Virtual Madness @ Etsy
Virtual Madness @ EtsyVirtual Madness @ Etsy
Virtual Madness @ EtsyNishan Subedi
 
Aplicacoes dinamicas Rails com Backbone
Aplicacoes dinamicas Rails com BackboneAplicacoes dinamicas Rails com Backbone
Aplicacoes dinamicas Rails com BackboneRafael Felix da Silva
 
Propel sfugmd
Propel sfugmdPropel sfugmd
Propel sfugmdiKlaus
 
Writing Maintainable JavaScript
Writing Maintainable JavaScriptWriting Maintainable JavaScript
Writing Maintainable JavaScriptAndrew Dupont
 
Introduction à CoffeeScript pour ParisRB
Introduction à CoffeeScript pour ParisRB Introduction à CoffeeScript pour ParisRB
Introduction à CoffeeScript pour ParisRB jhchabran
 
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
 
Understanding backbonejs
Understanding backbonejsUnderstanding backbonejs
Understanding backbonejsNick Lee
 
Hazelcast
HazelcastHazelcast
Hazelcastoztalip
 
TypeScript Introduction
TypeScript IntroductionTypeScript Introduction
TypeScript IntroductionDmitry Sheiko
 
Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-
Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-
Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-Tsuyoshi Yamamoto
 

Ähnlich wie Backbone intro (20)

Introducing CakeEntity
Introducing CakeEntityIntroducing CakeEntity
Introducing CakeEntity
 
Art of Javascript
Art of JavascriptArt of Javascript
Art of Javascript
 
Object-Oriented Javascript
Object-Oriented JavascriptObject-Oriented Javascript
Object-Oriented Javascript
 
Object-Oriented JavaScript
Object-Oriented JavaScriptObject-Oriented JavaScript
Object-Oriented JavaScript
 
Separation of concerns - DPC12
Separation of concerns - DPC12Separation of concerns - DPC12
Separation of concerns - DPC12
 
前端MVC 豆瓣说
前端MVC 豆瓣说前端MVC 豆瓣说
前端MVC 豆瓣说
 
JavaScript Refactoring
JavaScript RefactoringJavaScript Refactoring
JavaScript Refactoring
 
Secrets of JavaScript Libraries
Secrets of JavaScript LibrariesSecrets of JavaScript Libraries
Secrets of JavaScript Libraries
 
ES6 Overview
ES6 OverviewES6 Overview
ES6 Overview
 
Virtual Madness @ Etsy
Virtual Madness @ EtsyVirtual Madness @ Etsy
Virtual Madness @ Etsy
 
Aplicacoes dinamicas Rails com Backbone
Aplicacoes dinamicas Rails com BackboneAplicacoes dinamicas Rails com Backbone
Aplicacoes dinamicas Rails com Backbone
 
Propel sfugmd
Propel sfugmdPropel sfugmd
Propel sfugmd
 
Writing Maintainable JavaScript
Writing Maintainable JavaScriptWriting Maintainable JavaScript
Writing Maintainable JavaScript
 
Introduction à CoffeeScript pour ParisRB
Introduction à CoffeeScript pour ParisRB Introduction à CoffeeScript pour ParisRB
Introduction à CoffeeScript pour ParisRB
 
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
 
Understanding backbonejs
Understanding backbonejsUnderstanding backbonejs
Understanding backbonejs
 
Hazelcast
HazelcastHazelcast
Hazelcast
 
TypeScript Introduction
TypeScript IntroductionTypeScript Introduction
TypeScript Introduction
 
Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-
Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-
Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-
 
Advanced Silverlight
Advanced SilverlightAdvanced Silverlight
Advanced Silverlight
 

Kürzlich hochgeladen

'the Spring 2024- popular Fashion trends
'the Spring 2024- popular Fashion trends'the Spring 2024- popular Fashion trends
'the Spring 2024- popular Fashion trendsTangledThoughtsCO
 
labradorite energetic gems for well beings.pdf
labradorite energetic gems for well beings.pdflabradorite energetic gems for well beings.pdf
labradorite energetic gems for well beings.pdfAkrati jewels inc
 
《QUT毕业文凭网-认证昆士兰科技大学毕业证成绩单》
《QUT毕业文凭网-认证昆士兰科技大学毕业证成绩单》《QUT毕业文凭网-认证昆士兰科技大学毕业证成绩单》
《QUT毕业文凭网-认证昆士兰科技大学毕业证成绩单》rnrncn29
 
Call In girls Delhi Safdarjung Enclave/WhatsApp 🔝 97111⇛⇛47426
Call In girls Delhi Safdarjung Enclave/WhatsApp 🔝  97111⇛⇛47426Call In girls Delhi Safdarjung Enclave/WhatsApp 🔝  97111⇛⇛47426
Call In girls Delhi Safdarjung Enclave/WhatsApp 🔝 97111⇛⇛47426jennyeacort
 
Uttoxeter & Cheadle Voice, Issue 122.pdf
Uttoxeter & Cheadle Voice, Issue 122.pdfUttoxeter & Cheadle Voice, Issue 122.pdf
Uttoxeter & Cheadle Voice, Issue 122.pdfNoel Sergeant
 
8377877756 Full Enjoy @24/7 Call Girls In Mayur Vihar Delhi Ncr
8377877756 Full Enjoy @24/7 Call Girls In Mayur Vihar Delhi Ncr8377877756 Full Enjoy @24/7 Call Girls In Mayur Vihar Delhi Ncr
8377877756 Full Enjoy @24/7 Call Girls In Mayur Vihar Delhi Ncrdollysharma2066
 
83778-876O7, Cash On Delivery Call Girls In South- EX-(Delhi) Escorts Service...
83778-876O7, Cash On Delivery Call Girls In South- EX-(Delhi) Escorts Service...83778-876O7, Cash On Delivery Call Girls In South- EX-(Delhi) Escorts Service...
83778-876O7, Cash On Delivery Call Girls In South- EX-(Delhi) Escorts Service...dollysharma2066
 
8 Easy Ways to Keep Your Heart Healthy this Summer | Amit Kakkar Healthyway
8 Easy Ways to Keep Your Heart Healthy this Summer | Amit Kakkar Healthyway8 Easy Ways to Keep Your Heart Healthy this Summer | Amit Kakkar Healthyway
8 Easy Ways to Keep Your Heart Healthy this Summer | Amit Kakkar HealthywayAmit Kakkar Healthyway
 
Virat Kohli Centuries In Career Age Awards and Facts.pdf
Virat Kohli Centuries In Career Age Awards and Facts.pdfVirat Kohli Centuries In Career Age Awards and Facts.pdf
Virat Kohli Centuries In Career Age Awards and Facts.pdfkigaya33
 
BOOK NIGHT-Call Girls In Noida City Centre Delhi ☎️ 8377877756
BOOK NIGHT-Call Girls In Noida City Centre Delhi ☎️ 8377877756BOOK NIGHT-Call Girls In Noida City Centre Delhi ☎️ 8377877756
BOOK NIGHT-Call Girls In Noida City Centre Delhi ☎️ 8377877756dollysharma2066
 

Kürzlich hochgeladen (11)

'the Spring 2024- popular Fashion trends
'the Spring 2024- popular Fashion trends'the Spring 2024- popular Fashion trends
'the Spring 2024- popular Fashion trends
 
labradorite energetic gems for well beings.pdf
labradorite energetic gems for well beings.pdflabradorite energetic gems for well beings.pdf
labradorite energetic gems for well beings.pdf
 
《QUT毕业文凭网-认证昆士兰科技大学毕业证成绩单》
《QUT毕业文凭网-认证昆士兰科技大学毕业证成绩单》《QUT毕业文凭网-认证昆士兰科技大学毕业证成绩单》
《QUT毕业文凭网-认证昆士兰科技大学毕业证成绩单》
 
Call In girls Delhi Safdarjung Enclave/WhatsApp 🔝 97111⇛⇛47426
Call In girls Delhi Safdarjung Enclave/WhatsApp 🔝  97111⇛⇛47426Call In girls Delhi Safdarjung Enclave/WhatsApp 🔝  97111⇛⇛47426
Call In girls Delhi Safdarjung Enclave/WhatsApp 🔝 97111⇛⇛47426
 
Uttoxeter & Cheadle Voice, Issue 122.pdf
Uttoxeter & Cheadle Voice, Issue 122.pdfUttoxeter & Cheadle Voice, Issue 122.pdf
Uttoxeter & Cheadle Voice, Issue 122.pdf
 
Call Girls 9953525677 Call Girls In Delhi Call Girls 9953525677 Call Girls In...
Call Girls 9953525677 Call Girls In Delhi Call Girls 9953525677 Call Girls In...Call Girls 9953525677 Call Girls In Delhi Call Girls 9953525677 Call Girls In...
Call Girls 9953525677 Call Girls In Delhi Call Girls 9953525677 Call Girls In...
 
8377877756 Full Enjoy @24/7 Call Girls In Mayur Vihar Delhi Ncr
8377877756 Full Enjoy @24/7 Call Girls In Mayur Vihar Delhi Ncr8377877756 Full Enjoy @24/7 Call Girls In Mayur Vihar Delhi Ncr
8377877756 Full Enjoy @24/7 Call Girls In Mayur Vihar Delhi Ncr
 
83778-876O7, Cash On Delivery Call Girls In South- EX-(Delhi) Escorts Service...
83778-876O7, Cash On Delivery Call Girls In South- EX-(Delhi) Escorts Service...83778-876O7, Cash On Delivery Call Girls In South- EX-(Delhi) Escorts Service...
83778-876O7, Cash On Delivery Call Girls In South- EX-(Delhi) Escorts Service...
 
8 Easy Ways to Keep Your Heart Healthy this Summer | Amit Kakkar Healthyway
8 Easy Ways to Keep Your Heart Healthy this Summer | Amit Kakkar Healthyway8 Easy Ways to Keep Your Heart Healthy this Summer | Amit Kakkar Healthyway
8 Easy Ways to Keep Your Heart Healthy this Summer | Amit Kakkar Healthyway
 
Virat Kohli Centuries In Career Age Awards and Facts.pdf
Virat Kohli Centuries In Career Age Awards and Facts.pdfVirat Kohli Centuries In Career Age Awards and Facts.pdf
Virat Kohli Centuries In Career Age Awards and Facts.pdf
 
BOOK NIGHT-Call Girls In Noida City Centre Delhi ☎️ 8377877756
BOOK NIGHT-Call Girls In Noida City Centre Delhi ☎️ 8377877756BOOK NIGHT-Call Girls In Noida City Centre Delhi ☎️ 8377877756
BOOK NIGHT-Call Girls In Noida City Centre Delhi ☎️ 8377877756
 

Backbone intro

  • 1. get a backbone an intro to the javascript mvc framework
  • 2. outline • why you need an mvc framework • what backbone is • how we use it in workday
  • 4. persist on server, access via restful api RESTful request serv er response
  • 6. json object { “kittens”: [ { “id”: “1”, “name”: “Max”, "plaything": "catnip" }, { “id”: “2”, "name": "Orhan", "plaything": "sofa legs" } ] }
  • 7. $.ajax({ url: '/rest/kittens' success: function(response) { _.each(response.kittens, function(kitten) { var kittenTemplate = ...//some template // Go make all the table rows. $("#cat-container").append(kittenTemplate); }) } });
  • 8. catopia max catnip orhan sofa legs
  • 9. catopia max catnip orhan sofa legs
  • 10. <tr class=”kitten-row” kitten-id=”1”> <td class=”kitten-photo”><img src=”max.jpg”></td> <td class=”kitten-name”>max</td> <td class=”kitten-plaything”>catnip</td> <td class=”kitten-delete”><img src=”delete.jpg”></td> </tr> max catnip
  • 11. <tr class=”kitten-row” kitten-id=”1”> <td class=”kitten-photo”><img src=”max.jpg”></td> <td class=”kitten-name”>max</td> <td class=”kitten-plaything”>catnip</td> <td class=”kitten-delete”><img src=”delete.jpg”></td> </tr> max catnip
  • 12. max catnip $(“.kitten-delete”).click(function () { // Find the ID of the kitten var id = $(this).closest(“.kitten-row”).attr(“kitten-id”); // Do the delete request $.ajax( url: “/rest/kittens/1”, type: “DELETE” });
  • 13. max catnip $(“.kitten-delete”).click(function () { // Find the ID of the kitten var kittenRow = $(this).closest(“.kitten-row”); var id = kittenRow.attr(“kitten-id”); // Do the delete request $.ajax( url: “/rest/kittens/1”, type: “DELETE”, success: function () { kittenRow.remove(); } });
  • 14.
  • 15. i haz a sad my data is tightly coupled to my DOM
  • 17. if my data wasn’t coupled to the DOM?
  • 18. if my kittens could update themselves!
  • 19.
  • 20. javascript mvc frameworks backbone.js spine.js javascriptMVC is different to cappucino sencha widgets sproutcore UI elements
  • 21. backbone.js lightweight ~4kb one hard dependency: underscore.js compatible with jQuery or Zepto used by foursquare, trello, khan academy
  • 23. models where we keep our data + utility functions // Create a Kitten model by extending Backbone.Model var Kitten = Backbone.Model.extend({ // something we want all kittens to do play: function () { console.log("Playing with " + this.model.get("plaything")); } }
  • 24. models instantiating a model var max = new Kitten(); max.play();
  • 25. models access data via set and get can validate data easily // Create a Kitten model by extending Backbone.Model var Kitten = Backbone.Model.extend({ // validate our data by overriding the method // in Backbone.Model validate: function(attrs) { if (attrs.plaything == “dog”) { // error return “You haven’t watched enough Hanna-Barbera cartoons.” } } } // Instantiate a kitten. var max = new Kitten(); max.set({plaything: "twine"});
  • 26. collections arrays of model instances // Create a collection of kittens! var Kittens = Backbone.Collection.extend({ model: Kitten // default model } var kittens = new Kittens; kittens.add({name: “Max”}); whenever you add a new item, kittens.add({name: “Orhan”}); an add event is fired. useful! e.g. kittens.bind(add, function(kitten) { alert(“Hi “ + kitten.get(“name”)); }
  • 27. collections populating collections var Kittens = Backbone.Collection.extend({ model: Kitten url: ‘/rest/kittens’ } var kittens = new Kittens; kittens.fetch();
  • 28. collections syncing with the server var Kittens = Backbone.Collection.extend({ model: Kitten url: ‘/rest/kittens’ } var kittens = new Kittens; kittens.fetch();
  • 29. models syncing with the server var Kitten = Backbone.Model.extend({ url: ‘/rest/kittens’ }
  • 30. collections backbone.sync The default sync handler maps CRUD to REST like so: ◦ create → POST   /collection ◦ read → GET   /collection[/id] ◦ update → PUT   /collection/id ◦ delete → DELETE   /collection/id
  • 31. each model has an associated view max has a model view both models are in a Kittens collection (they could be in others too! like a CuteThings collection. doesn’t have orhan has a to be a 1-1 mapping) model view
  • 32. views let’s create views for our kittens // Getting Max out of our kitten collection, he had an ID of 1 var max = kittens.get(1); // We’ll look at the view in detail next new KittenView({model: max});
  • 33. views var KittenView = Backbone.View.extend({ tagName: “tr”, className: “kitten-row”, template: _.template($(“#kitten-template”).html()), render: function() { $(this.el).html(this.template(this.model.toJSON()))); return this; } }); this will return some HTML all views have an associated element
  • 34. views let’s do some add in that feature var KittenView = Backbone.View.extend({ tagName: “tr”, className: “kitten-row”, template: _.template($(“#kitten-template”).html()), events: { “keypress .delete-icon”: “destroyKitten” } destroyKitten: function() { this.model.destroy(); } render: function() { $(this.el).html(this.template(this.model.toJSON()))); return this; } });
  • 35. workday models views notifications notification view starred items starred item view collections notifications appview starred items
  • 36. moar backbone.js & underscore.js docs backbone demo: todos // small well-commented app javascript web applications // an o’reilly book

Hinweis der Redaktion

  1. \n
  2. \n
  3. \n
  4. \n
  5. \n
  6. \n
  7. \n
  8. \n
  9. \n
  10. \n
  11. \n
  12. \n
  13. \n
  14. \n
  15. \n
  16. \n
  17. \n
  18. \n
  19. \n
  20. \n
  21. \n
  22. \n
  23. \n
  24. \n
  25. \n
  26. \n
  27. \n
  28. \n
  29. \n
  30. \n
  31. \n
  32. \n
  33. \n
  34. \n
  35. \n
  36. \n