SlideShare a Scribd company logo
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 Objects
Jeff Prestes
 
Attribute
AttributeAttribute
Attribute
Luke Smith
 
Beacons, Raspberry Pi & Node.js
Beacons, Raspberry Pi & Node.jsBeacons, Raspberry Pi & Node.js
Beacons, Raspberry Pi & Node.js
Jeff 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 Quinones
alertchair8725
 
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 Development
Jay Harris
 
Why (I think) CoffeeScript Is Awesome
Why (I think) CoffeeScript Is AwesomeWhy (I think) CoffeeScript Is Awesome
Why (I think) CoffeeScript Is Awesome
Jo Cranford
 
Kotlin Generation
Kotlin GenerationKotlin Generation
Kotlin Generation
Minseo Chayabanjonglerd
 
Chapter 4
Chapter 4Chapter 4
Chapter 4
EasyStudy3
 
201204 random clustering
201204 random clustering201204 random clustering
201204 random clustering
pluskjw
 
Epic South Disasters
Epic South DisastersEpic South Disasters
Epic South Disasters
Christopher Adams
 
International News | World News
International News | World NewsInternational News | World News
International News | World News
productiveengin27
 
FRP and Bacon.js
FRP and Bacon.jsFRP and Bacon.js
FRP and Bacon.js
Starbuildr
 
[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
Flavio Poletti
 
Programmers, communicate your intentions
Programmers, communicate your intentionsProgrammers, communicate your intentions
Programmers, communicate your intentions
Yael Zaritsky Perez
 
Say It With Javascript
Say It With JavascriptSay It With Javascript
Say It With Javascript
Giovanni Scerra ☃
 
Mongoose and MongoDB 101
Mongoose and MongoDB 101Mongoose and MongoDB 101
Mongoose and MongoDB 101
Will 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 Code
nabeelahali
 
Remixing Confluence With Speakeasy
Remixing Confluence With SpeakeasyRemixing Confluence With Speakeasy
Remixing Confluence With Speakeasynabeelahali
 
Arduino JumpStart
Arduino JumpStartArduino JumpStart
Arduino JumpStart
nabeelahali
 
How to Teach Your Grandmother
How to Teach Your GrandmotherHow to Teach Your Grandmother
How to Teach Your Grandmother
nabeelahali
 
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 2017
Activate
 
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
LinkedIn
 
Hype vs. Reality: The AI Explainer
Hype vs. Reality: The AI ExplainerHype vs. Reality: The AI Explainer
Hype vs. Reality: The AI Explainer
Luminary 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 CakeEntity
Basuke Suzuki
 
Art of Javascript
Art of JavascriptArt of Javascript
Art of Javascript
Tarek Yehia
 
Object-Oriented JavaScript
Object-Oriented JavaScriptObject-Oriented JavaScript
Object-Oriented JavaScript
kvangork
 
Object-Oriented Javascript
Object-Oriented JavascriptObject-Oriented Javascript
Object-Oriented Javascript
kvangork
 
前端MVC 豆瓣说
前端MVC 豆瓣说前端MVC 豆瓣说
前端MVC 豆瓣说Ting Lv
 
JavaScript Refactoring
JavaScript RefactoringJavaScript Refactoring
JavaScript Refactoring
Krzysztof Szafranek
 
Secrets of JavaScript Libraries
Secrets of JavaScript LibrariesSecrets of JavaScript Libraries
Secrets of JavaScript Libraries
jeresig
 
ES6 Overview
ES6 OverviewES6 Overview
ES6 Overview
Bruno Scopelliti
 
Virtual Madness @ Etsy
Virtual Madness @ EtsyVirtual Madness @ Etsy
Virtual Madness @ Etsy
Nishan Subedi
 
Aplicacoes dinamicas Rails com Backbone
Aplicacoes dinamicas Rails com BackboneAplicacoes dinamicas Rails com Backbone
Aplicacoes dinamicas Rails com Backbone
Rafael Felix da Silva
 
Propel sfugmd
Propel sfugmdPropel sfugmd
Propel sfugmdiKlaus
 
Writing Maintainable JavaScript
Writing Maintainable JavaScriptWriting Maintainable JavaScript
Writing Maintainable JavaScript
Andrew 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 backbonejs
Nick Lee
 
Hazelcast
HazelcastHazelcast
Hazelcast
oztalip
 
TypeScript Introduction
TypeScript IntroductionTypeScript Introduction
TypeScript Introduction
Dmitry Sheiko
 
Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-
Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-
Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-
Tsuyoshi Yamamoto
 
Advanced Silverlight
Advanced SilverlightAdvanced Silverlight
Advanced Silverlight
Jeff Blankenburg
 

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

erevna-influencers-social-media-stin-ellada
erevna-influencers-social-media-stin-elladaerevna-influencers-social-media-stin-ellada
erevna-influencers-social-media-stin-ellada
rvlassopoulou
 
Gujarat Details in Hindi for children's for presentation in school
Gujarat Details in Hindi for children's for presentation in schoolGujarat Details in Hindi for children's for presentation in school
Gujarat Details in Hindi for children's for presentation in school
shouryajoshi5
 
Johnny Depp Long Hair: A Signature Look Through the Years
Johnny Depp Long Hair: A Signature Look Through the YearsJohnny Depp Long Hair: A Signature Look Through the Years
Johnny Depp Long Hair: A Signature Look Through the Years
greendigital
 
MRS PUNE 2024 - WINNER AMRUTHAA UTTAM JAGDHANE
MRS PUNE 2024 - WINNER AMRUTHAA UTTAM JAGDHANEMRS PUNE 2024 - WINNER AMRUTHAA UTTAM JAGDHANE
MRS PUNE 2024 - WINNER AMRUTHAA UTTAM JAGDHANE
DK PAGEANT
 
What To Do If Your Ring Is Too Big? Must Read
What To Do If Your Ring Is Too Big? Must ReadWhat To Do If Your Ring Is Too Big? Must Read
What To Do If Your Ring Is Too Big? Must Read
Andrews Jewelers
 
Exploring Ancient Mysteries Visions of Atlantis.pptx
Exploring Ancient Mysteries Visions of Atlantis.pptxExploring Ancient Mysteries Visions of Atlantis.pptx
Exploring Ancient Mysteries Visions of Atlantis.pptx
Ruth Elisabeth Hancock
 
From Stress to Success How Oakland's Corporate Wellness Programs are Cultivat...
From Stress to Success How Oakland's Corporate Wellness Programs are Cultivat...From Stress to Success How Oakland's Corporate Wellness Programs are Cultivat...
From Stress to Success How Oakland's Corporate Wellness Programs are Cultivat...
Kitchen on Fire
 
Care Instructions for Activewear & Swim Suits.pdf
Care Instructions for Activewear & Swim Suits.pdfCare Instructions for Activewear & Swim Suits.pdf
Care Instructions for Activewear & Swim Suits.pdf
sundazesurf80
 
30 Manipulation Techniques to be a smart person in society (1).pdf
30 Manipulation Techniques to be a smart person in society (1).pdf30 Manipulation Techniques to be a smart person in society (1).pdf
30 Manipulation Techniques to be a smart person in society (1).pdf
minaserver6679
 
Unique Wedding Bands For Women Who Want To Stand Out.pptx
Unique Wedding Bands For Women Who Want To Stand Out.pptxUnique Wedding Bands For Women Who Want To Stand Out.pptx
Unique Wedding Bands For Women Who Want To Stand Out.pptx
Andrews Jewelers
 
La transidentité, un sujet qui fractionne les Français
La transidentité, un sujet qui fractionne les FrançaisLa transidentité, un sujet qui fractionne les Français
La transidentité, un sujet qui fractionne les Français
Ipsos France
 
EXPERIENCE MONSTER BITES STREETWEAR APPAREL
EXPERIENCE MONSTER BITES STREETWEAR APPARELEXPERIENCE MONSTER BITES STREETWEAR APPAREL
EXPERIENCE MONSTER BITES STREETWEAR APPAREL
6ctbkfpdxz
 

Recently uploaded (12)

erevna-influencers-social-media-stin-ellada
erevna-influencers-social-media-stin-elladaerevna-influencers-social-media-stin-ellada
erevna-influencers-social-media-stin-ellada
 
Gujarat Details in Hindi for children's for presentation in school
Gujarat Details in Hindi for children's for presentation in schoolGujarat Details in Hindi for children's for presentation in school
Gujarat Details in Hindi for children's for presentation in school
 
Johnny Depp Long Hair: A Signature Look Through the Years
Johnny Depp Long Hair: A Signature Look Through the YearsJohnny Depp Long Hair: A Signature Look Through the Years
Johnny Depp Long Hair: A Signature Look Through the Years
 
MRS PUNE 2024 - WINNER AMRUTHAA UTTAM JAGDHANE
MRS PUNE 2024 - WINNER AMRUTHAA UTTAM JAGDHANEMRS PUNE 2024 - WINNER AMRUTHAA UTTAM JAGDHANE
MRS PUNE 2024 - WINNER AMRUTHAA UTTAM JAGDHANE
 
What To Do If Your Ring Is Too Big? Must Read
What To Do If Your Ring Is Too Big? Must ReadWhat To Do If Your Ring Is Too Big? Must Read
What To Do If Your Ring Is Too Big? Must Read
 
Exploring Ancient Mysteries Visions of Atlantis.pptx
Exploring Ancient Mysteries Visions of Atlantis.pptxExploring Ancient Mysteries Visions of Atlantis.pptx
Exploring Ancient Mysteries Visions of Atlantis.pptx
 
From Stress to Success How Oakland's Corporate Wellness Programs are Cultivat...
From Stress to Success How Oakland's Corporate Wellness Programs are Cultivat...From Stress to Success How Oakland's Corporate Wellness Programs are Cultivat...
From Stress to Success How Oakland's Corporate Wellness Programs are Cultivat...
 
Care Instructions for Activewear & Swim Suits.pdf
Care Instructions for Activewear & Swim Suits.pdfCare Instructions for Activewear & Swim Suits.pdf
Care Instructions for Activewear & Swim Suits.pdf
 
30 Manipulation Techniques to be a smart person in society (1).pdf
30 Manipulation Techniques to be a smart person in society (1).pdf30 Manipulation Techniques to be a smart person in society (1).pdf
30 Manipulation Techniques to be a smart person in society (1).pdf
 
Unique Wedding Bands For Women Who Want To Stand Out.pptx
Unique Wedding Bands For Women Who Want To Stand Out.pptxUnique Wedding Bands For Women Who Want To Stand Out.pptx
Unique Wedding Bands For Women Who Want To Stand Out.pptx
 
La transidentité, un sujet qui fractionne les Français
La transidentité, un sujet qui fractionne les FrançaisLa transidentité, un sujet qui fractionne les Français
La transidentité, un sujet qui fractionne les Français
 
EXPERIENCE MONSTER BITES STREETWEAR APPAREL
EXPERIENCE MONSTER BITES STREETWEAR APPARELEXPERIENCE MONSTER BITES STREETWEAR APPAREL
EXPERIENCE MONSTER BITES STREETWEAR APPAREL
 

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