SlideShare a Scribd company logo
1 of 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

More Related Content

What's hot

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
 

What's hot (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
 

Viewers also liked

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
 

Viewers also liked (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
 

Similar to 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
 

Similar to 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
 

Recently uploaded

Navigating Hypnotherapy Training: 7 Essential Considerations
Navigating Hypnotherapy Training: 7 Essential ConsiderationsNavigating Hypnotherapy Training: 7 Essential Considerations
Navigating Hypnotherapy Training: 7 Essential Considerationsrenewed edge
 
"Paltr Packaging: Streamlined Order Process for Seamless Deliveries"
"Paltr Packaging: Streamlined Order Process for Seamless Deliveries""Paltr Packaging: Streamlined Order Process for Seamless Deliveries"
"Paltr Packaging: Streamlined Order Process for Seamless Deliveries"Aarisha Shaikh
 
UNIVERSAL HUMAN VALUES - Harmony in the Family and Society
UNIVERSAL HUMAN VALUES - Harmony in the Family and SocietyUNIVERSAL HUMAN VALUES - Harmony in the Family and Society
UNIVERSAL HUMAN VALUES - Harmony in the Family and SocietyChandrakantDivate1
 
Lesotho history, Basotho languages, Basotho mode of transport
Lesotho history, Basotho languages, Basotho mode of transportLesotho history, Basotho languages, Basotho mode of transport
Lesotho history, Basotho languages, Basotho mode of transporttobatsitlotliso004
 
PRINCESS OF DESIRE: MISADVENTURES OF A YOUNG GIRL
PRINCESS OF DESIRE:  MISADVENTURES OF A YOUNG GIRLPRINCESS OF DESIRE:  MISADVENTURES OF A YOUNG GIRL
PRINCESS OF DESIRE: MISADVENTURES OF A YOUNG GIRLmarianasoeiro3
 
Ladies kitty party invitation messages and greetings.pdf
Ladies kitty party invitation messages and greetings.pdfLadies kitty party invitation messages and greetings.pdf
Ladies kitty party invitation messages and greetings.pdfShort Good Quotes
 
Shining Bright: Diya Jain Represents Delhi As Miss Teen India Finalist-2024
Shining Bright: Diya Jain Represents Delhi As Miss Teen India Finalist-2024Shining Bright: Diya Jain Represents Delhi As Miss Teen India Finalist-2024
Shining Bright: Diya Jain Represents Delhi As Miss Teen India Finalist-2024DK PAGEANT
 
Top 10 Moisturising Cream Brands In India - Stelon Biotech
Top 10 Moisturising Cream Brands In India - Stelon BiotechTop 10 Moisturising Cream Brands In India - Stelon Biotech
Top 10 Moisturising Cream Brands In India - Stelon BiotechStelon Biotech
 
UNIVERSAL HUMAN VALUES - INTRODUCTION TO VALUE EDUCATION
 UNIVERSAL HUMAN VALUES - INTRODUCTION TO VALUE EDUCATION UNIVERSAL HUMAN VALUES - INTRODUCTION TO VALUE EDUCATION
UNIVERSAL HUMAN VALUES - INTRODUCTION TO VALUE EDUCATIONChandrakantDivate1
 
2024_Rupantara Jogare Namajapa II Nishitharanjan
2024_Rupantara Jogare Namajapa II Nishitharanjan2024_Rupantara Jogare Namajapa II Nishitharanjan
2024_Rupantara Jogare Namajapa II NishitharanjanNishitharanjan Rout
 
SINGLE PARENTS LONE PARENTHOOD: RESPONSIBILITY
SINGLE PARENTS LONE PARENTHOOD: RESPONSIBILITYSINGLE PARENTS LONE PARENTHOOD: RESPONSIBILITY
SINGLE PARENTS LONE PARENTHOOD: RESPONSIBILITYNgcNguyn951014
 
UNIVERSAL HUMAN VALUES -Harmony in the Human Being
UNIVERSAL HUMAN VALUES -Harmony in the Human BeingUNIVERSAL HUMAN VALUES -Harmony in the Human Being
UNIVERSAL HUMAN VALUES -Harmony in the Human BeingChandrakantDivate1
 
Style Victorious Cute Outfits for Winners
Style Victorious Cute Outfits for WinnersStyle Victorious Cute Outfits for Winners
Style Victorious Cute Outfits for Winnersolva0212
 

Recently uploaded (14)

Navigating Hypnotherapy Training: 7 Essential Considerations
Navigating Hypnotherapy Training: 7 Essential ConsiderationsNavigating Hypnotherapy Training: 7 Essential Considerations
Navigating Hypnotherapy Training: 7 Essential Considerations
 
"Paltr Packaging: Streamlined Order Process for Seamless Deliveries"
"Paltr Packaging: Streamlined Order Process for Seamless Deliveries""Paltr Packaging: Streamlined Order Process for Seamless Deliveries"
"Paltr Packaging: Streamlined Order Process for Seamless Deliveries"
 
UNIVERSAL HUMAN VALUES - Harmony in the Family and Society
UNIVERSAL HUMAN VALUES - Harmony in the Family and SocietyUNIVERSAL HUMAN VALUES - Harmony in the Family and Society
UNIVERSAL HUMAN VALUES - Harmony in the Family and Society
 
Lesotho history, Basotho languages, Basotho mode of transport
Lesotho history, Basotho languages, Basotho mode of transportLesotho history, Basotho languages, Basotho mode of transport
Lesotho history, Basotho languages, Basotho mode of transport
 
PRINCESS OF DESIRE: MISADVENTURES OF A YOUNG GIRL
PRINCESS OF DESIRE:  MISADVENTURES OF A YOUNG GIRLPRINCESS OF DESIRE:  MISADVENTURES OF A YOUNG GIRL
PRINCESS OF DESIRE: MISADVENTURES OF A YOUNG GIRL
 
Ladies kitty party invitation messages and greetings.pdf
Ladies kitty party invitation messages and greetings.pdfLadies kitty party invitation messages and greetings.pdf
Ladies kitty party invitation messages and greetings.pdf
 
Shining Bright: Diya Jain Represents Delhi As Miss Teen India Finalist-2024
Shining Bright: Diya Jain Represents Delhi As Miss Teen India Finalist-2024Shining Bright: Diya Jain Represents Delhi As Miss Teen India Finalist-2024
Shining Bright: Diya Jain Represents Delhi As Miss Teen India Finalist-2024
 
Top 10 Moisturising Cream Brands In India - Stelon Biotech
Top 10 Moisturising Cream Brands In India - Stelon BiotechTop 10 Moisturising Cream Brands In India - Stelon Biotech
Top 10 Moisturising Cream Brands In India - Stelon Biotech
 
UNIVERSAL HUMAN VALUES - INTRODUCTION TO VALUE EDUCATION
 UNIVERSAL HUMAN VALUES - INTRODUCTION TO VALUE EDUCATION UNIVERSAL HUMAN VALUES - INTRODUCTION TO VALUE EDUCATION
UNIVERSAL HUMAN VALUES - INTRODUCTION TO VALUE EDUCATION
 
2024_Rupantara Jogare Namajapa II Nishitharanjan
2024_Rupantara Jogare Namajapa II Nishitharanjan2024_Rupantara Jogare Namajapa II Nishitharanjan
2024_Rupantara Jogare Namajapa II Nishitharanjan
 
SINGLE PARENTS LONE PARENTHOOD: RESPONSIBILITY
SINGLE PARENTS LONE PARENTHOOD: RESPONSIBILITYSINGLE PARENTS LONE PARENTHOOD: RESPONSIBILITY
SINGLE PARENTS LONE PARENTHOOD: RESPONSIBILITY
 
@Abortion clinic tablets Kuwait (+918133066128) Abortion Pills IN Kuwait
@Abortion clinic tablets Kuwait (+918133066128) Abortion Pills IN Kuwait@Abortion clinic tablets Kuwait (+918133066128) Abortion Pills IN Kuwait
@Abortion clinic tablets Kuwait (+918133066128) Abortion Pills IN Kuwait
 
UNIVERSAL HUMAN VALUES -Harmony in the Human Being
UNIVERSAL HUMAN VALUES -Harmony in the Human BeingUNIVERSAL HUMAN VALUES -Harmony in the Human Being
UNIVERSAL HUMAN VALUES -Harmony in the Human Being
 
Style Victorious Cute Outfits for Winners
Style Victorious Cute Outfits for WinnersStyle Victorious Cute Outfits for Winners
Style Victorious Cute Outfits for Winners
 

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

Editor's Notes

  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