SlideShare une entreprise Scribd logo
1  sur  16
Backbone.js
  Simple Tutorial
     by @fallroot
Backbone.js

Backbone supplies structure to JavaScript-heavy 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 application over a RESTful

JSON interface.
$ rails new todoapp                                                     Back-end
$ cd todoapp

$ rm public/index.html

$ rails g scaffold todo title:string done:boolean
                                                    •   Ruby on Rails
$ rake db:migrate
                                                        •   3.1.0 RC5
$ rails s
<script type="text/template"></script>         Dependency
<script src="jquery.js / zepto.js"></script>
<script src="underscore.js"></script>
<script src="backbone.js"></script>

<script src="my-scripts.js"></script>
var Item = Backbone.Model.extend({
  urlRoot: '/todos'
                                                                    POST
});

var item = new Item({
  title: 'Create new todo'
});
                                     •   Backbone.Model.extend(properties,
item.save();
                                         [classProperties])
                                     •   model.save([attributes], [options])
                                     •   model.url()
                                     •   model.urlRoot
                                         •   /urlRoot/id
var Item = Backbone.Model.extend({
  urlRoot: '/todos'
                                                                                     PUT
});

var item = new Item({
  title: 'Create another todo'
});
                                                 •   _.bind(function, object, [*arguments])
item.save();                                     •   _.delay(function, wait, [*arguments])
var save = _.bind(item.save, item);
_.delay(save, 5000, {title: 'Title updated'});
var Item = Backbone.Model.extend({
  urlRoot: '/todos'
                                                                    DELETE
});

var item = new Item({
  title: 'This will be deleted'
});
                                             •   model.destroy([options])
item.save();

_.delay(_.bind(item.destroy, item), 5000);
var Item = Backbone.Model.extend({
  urlRoot: '/todos'
                                                                                        GET
});

var ItemView = Backbone.View.extend({
 tagName: 'li',

 initialize: function() {                          •   Backbone.View.extend(properties,
   this.model.bind('change', this.render, this);
                                                       [classProperties])
 },
                                                   •   model.fetch([options])
  render: function() {
    this.el.innerHTML = this.model.get('title');
                                                   •   model.get(attribute)
    return this;                                   •   object.bind(event, callback, [context])
  }
});

var item = new Item({id: 1});
item.fetch();

var itemView = new ItemView({model: item});
$('#todos').append(itemView.el);
var Item = Backbone.Model.extend();                                      Collection
var ItemView = Backbone.View.extend({
 tagName: 'li',

 initialize: function() {
   this.model.bind('change', this.render, this);
 },                                                •   Backbone.Collection.extend(properties,
  render: function() {                                 [classProperties])
    this.el.innerHTML = this.model.get('title');
    return this;
                                                   •   collection.fetch([options])
  }                                                •   collection.model
});
                                                   •   collection.url or collection.url()
var Item = Backbone.Model.extend();
    var List = Backbone.Collection.extend({
                                                                                   Collection
var ItemView = Backbone.View.extend({
      model: Item,
 tagName: 'li',
      url : '/todos'
    });
 initialize: function() {
    var ListView = Backbone.View.extend({
   this.model.bind('change', this.render, this);
 }, el: $('#todos'),                                         •   Backbone.Collection.extend(properties,
       initialize: function() {
  render: function() {
         this.collection.bind('reset', this.render, this);       [classProperties])
    this.el.innerHTML = this.model.get('title');
         this.collection.fetch();                            •   collection.fetch([options])
    return this;
       },
  }                                                          •   collection.model
}); render: function() {
         var el = this.el;                                   •   collection.url or collection.url()
         this.collection.each(function(item) {
           var itemView = new ItemView({model: item});
           el.append(itemView.render().el);
         });
         return this;
       }
     });

   new ListView({collection: new List});
var Router = Backbone.Router.extend({
 routes: {
                                                                                 Router
   '*action': 'actionCallback'
 },

  actionCallback: function(action) {
    document.body.innerHTML = action;
  }                                               •   Backbone.Router.extend(properties,
});                                                   [classProperties])

var router = new Router();                        •   router.navigate(fragment, [triggerRoute])
Backbone.history.start();                         •   Backbone.history.start([options])

router.navigate('started', true);
                                                  •   URL Fragment
var navigate = _.bind(router.navigate, router);
_.delay(navigate, 3000, 'moved', true);           •   history.pushState / popState
                                                  •   window.onhashchange
                                                      •   IE8
                                                  •   polling if not supported
<script type="text/template" id="item-template">
 <p class="done">
                                                                                  Template
  <input type="checkbox" <% if (done) { %>checked<% } %>>
 </p>
 <p class="title"><%= title %></p>
 <p class="commands">
  <button class="edit">Edit</button>
  <button class="remove">Remove</button>
 </p>                                                       •   _.template(templateString, [context])
</script>
                                                            •   model.toJSON()
<script type="text/template" id="item-template">
 <p class="done">
   var Item = Backbone.Model.extend({
                                                                                       Template
  <input type="checkbox" <% if (done) { %>checked<% } %>>
     urlRoot: '/todos'
 </p>
   });
 <p class="title"><%= title %></p>
 <p class="commands">
   var ItemView = Backbone.View.extend({
  <button class="edit">Edit</button>
     tagName: 'li',
  <button class="remove">Remove</button>
 </p>
     template: _.template($('#item-template').html()),
                                                                 •   _.template(templateString, [context])
</script>
     initialize: function() {
                                                                 •   model.toJSON()
      this.model.bind('change', this.render, this);
    },

     render: function() {
       this.el.innerHTML = this.template(this.model.toJSON());
       return this;
     }
   });

   var item = new Item({id: 1});
   item.fetch();

   var itemView = new ItemView({model: item});
   $('#todos').append(itemView.el);
All Together
Conclusion

•   For JavaScript Heavy Application
    •   Single-Page Application
•   Skinny Back-end
    •   RESTful JSON Interface
Backbone.js Basics for Building JavaScript Apps

Contenu connexe

Tendances

Be lazy, be ESI: HTTP caching and Symfony2 @ PHPDay 2011 05-13-2011
 Be lazy, be ESI: HTTP caching and Symfony2 @ PHPDay 2011 05-13-2011 Be lazy, be ESI: HTTP caching and Symfony2 @ PHPDay 2011 05-13-2011
Be lazy, be ESI: HTTP caching and Symfony2 @ PHPDay 2011 05-13-2011Alessandro Nadalin
 
Nickolay Shmalenuk.Render api eng.DrupalCamp Kyiv 2011
Nickolay Shmalenuk.Render api eng.DrupalCamp Kyiv 2011Nickolay Shmalenuk.Render api eng.DrupalCamp Kyiv 2011
Nickolay Shmalenuk.Render api eng.DrupalCamp Kyiv 2011camp_drupal_ua
 
Be RESTful (Symfony Camp 2008)
Be RESTful (Symfony Camp 2008)Be RESTful (Symfony Camp 2008)
Be RESTful (Symfony Camp 2008)Fabien Potencier
 
Building Smart Async Functions For Mobile
Building Smart Async Functions For MobileBuilding Smart Async Functions For Mobile
Building Smart Async Functions For MobileGlan Thomas
 
WordPress plugin #3
WordPress plugin #3WordPress plugin #3
WordPress plugin #3giwoolee
 
jQuery Rescue Adventure
jQuery Rescue AdventurejQuery Rescue Adventure
jQuery Rescue AdventureAllegient
 
AngularJS Services
AngularJS ServicesAngularJS Services
AngularJS ServicesEyal Vardi
 
[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
 
AngularJS - $http & $resource Services
AngularJS - $http & $resource ServicesAngularJS - $http & $resource Services
AngularJS - $http & $resource ServicesEyal Vardi
 
Viastudy ef core_cheat_sheet
Viastudy ef core_cheat_sheetViastudy ef core_cheat_sheet
Viastudy ef core_cheat_sheetimdurgesh
 
Drupal - dbtng 25th Anniversary Edition
Drupal - dbtng 25th Anniversary EditionDrupal - dbtng 25th Anniversary Edition
Drupal - dbtng 25th Anniversary Editionddiers
 
jQuery Namespace Pattern
jQuery Namespace PatternjQuery Namespace Pattern
jQuery Namespace PatternDiego Fleury
 
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 $Provide Service
AngularJS $Provide ServiceAngularJS $Provide Service
AngularJS $Provide ServiceEyal Vardi
 
JavaScript in Drupal 7: What developers need to know
JavaScript in Drupal 7: What developers need to knowJavaScript in Drupal 7: What developers need to know
JavaScript in Drupal 7: What developers need to knowkatbailey
 
Beyond the DOM: Sane Structure for JS Apps
Beyond the DOM: Sane Structure for JS AppsBeyond the DOM: Sane Structure for JS Apps
Beyond the DOM: Sane Structure for JS AppsRebecca Murphey
 

Tendances (20)

Be lazy, be ESI: HTTP caching and Symfony2 @ PHPDay 2011 05-13-2011
 Be lazy, be ESI: HTTP caching and Symfony2 @ PHPDay 2011 05-13-2011 Be lazy, be ESI: HTTP caching and Symfony2 @ PHPDay 2011 05-13-2011
Be lazy, be ESI: HTTP caching and Symfony2 @ PHPDay 2011 05-13-2011
 
Nickolay Shmalenuk.Render api eng.DrupalCamp Kyiv 2011
Nickolay Shmalenuk.Render api eng.DrupalCamp Kyiv 2011Nickolay Shmalenuk.Render api eng.DrupalCamp Kyiv 2011
Nickolay Shmalenuk.Render api eng.DrupalCamp Kyiv 2011
 
Be RESTful (Symfony Camp 2008)
Be RESTful (Symfony Camp 2008)Be RESTful (Symfony Camp 2008)
Be RESTful (Symfony Camp 2008)
 
Building Smart Async Functions For Mobile
Building Smart Async Functions For MobileBuilding Smart Async Functions For Mobile
Building Smart Async Functions For Mobile
 
WordPress plugin #3
WordPress plugin #3WordPress plugin #3
WordPress plugin #3
 
Jquery Fundamentals
Jquery FundamentalsJquery Fundamentals
Jquery Fundamentals
 
jQuery Rescue Adventure
jQuery Rescue AdventurejQuery Rescue Adventure
jQuery Rescue Adventure
 
AngularJS Services
AngularJS ServicesAngularJS Services
AngularJS Services
 
[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
 
AngularJS - $http & $resource Services
AngularJS - $http & $resource ServicesAngularJS - $http & $resource Services
AngularJS - $http & $resource Services
 
Viastudy ef core_cheat_sheet
Viastudy ef core_cheat_sheetViastudy ef core_cheat_sheet
Viastudy ef core_cheat_sheet
 
Drupal - dbtng 25th Anniversary Edition
Drupal - dbtng 25th Anniversary EditionDrupal - dbtng 25th Anniversary Edition
Drupal - dbtng 25th Anniversary Edition
 
jQuery Namespace Pattern
jQuery Namespace PatternjQuery Namespace Pattern
jQuery Namespace Pattern
 
jQuery Presentasion
jQuery PresentasionjQuery Presentasion
jQuery Presentasion
 
Upgrade your javascript to drupal 8
Upgrade your javascript to drupal 8Upgrade your javascript to drupal 8
Upgrade your javascript to drupal 8
 
I os 04
I os 04I os 04
I os 04
 
AngularJS $Provide Service
AngularJS $Provide ServiceAngularJS $Provide Service
AngularJS $Provide Service
 
JavaScript in Drupal 7: What developers need to know
JavaScript in Drupal 7: What developers need to knowJavaScript in Drupal 7: What developers need to know
JavaScript in Drupal 7: What developers need to know
 
Backbone js
Backbone jsBackbone js
Backbone js
 
Beyond the DOM: Sane Structure for JS Apps
Beyond the DOM: Sane Structure for JS AppsBeyond the DOM: Sane Structure for JS Apps
Beyond the DOM: Sane Structure for JS Apps
 

Similaire à Backbone.js Basics for Building JavaScript Apps

Understanding backbonejs
Understanding backbonejsUnderstanding backbonejs
Understanding backbonejsNick Lee
 
Aplicacoes dinamicas Rails com Backbone
Aplicacoes dinamicas Rails com BackboneAplicacoes dinamicas Rails com Backbone
Aplicacoes dinamicas Rails com BackboneRafael Felix da Silva
 
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
 
前端MVC 豆瓣说
前端MVC 豆瓣说前端MVC 豆瓣说
前端MVC 豆瓣说Ting Lv
 
Client-side MVC with Backbone.js (reloaded)
Client-side MVC with Backbone.js (reloaded)Client-side MVC with Backbone.js (reloaded)
Client-side MVC with Backbone.js (reloaded)iloveigloo
 
Client-side MVC with Backbone.js
Client-side MVC with Backbone.js Client-side MVC with Backbone.js
Client-side MVC with Backbone.js iloveigloo
 
Django class based views (Dutch Django meeting presentation)
Django class based views (Dutch Django meeting presentation)Django class based views (Dutch Django meeting presentation)
Django class based views (Dutch Django meeting presentation)Reinout van Rees
 
Backbonejs for beginners
Backbonejs for beginnersBackbonejs for beginners
Backbonejs for beginnersDivakar Gu
 
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
 
Javascript MVC & Backbone Tips & Tricks
Javascript MVC & Backbone Tips & TricksJavascript MVC & Backbone Tips & Tricks
Javascript MVC & Backbone Tips & TricksHjörtur Hilmarsson
 
Django Class-based views (Slovenian)
Django Class-based views (Slovenian)Django Class-based views (Slovenian)
Django Class-based views (Slovenian)Luka Zakrajšek
 
laravel tricks in 50minutes
laravel tricks in 50minuteslaravel tricks in 50minutes
laravel tricks in 50minutesBarang CK
 
Introducing CakeEntity
Introducing CakeEntityIntroducing CakeEntity
Introducing CakeEntityBasuke Suzuki
 
jQuery Data Manipulate API - A source code dissecting journey
jQuery Data Manipulate API - A source code dissecting journeyjQuery Data Manipulate API - A source code dissecting journey
jQuery Data Manipulate API - A source code dissecting journeyHuiyi Yan
 
Django Rest Framework and React and Redux, Oh My!
Django Rest Framework and React and Redux, Oh My!Django Rest Framework and React and Redux, Oh My!
Django Rest Framework and React and Redux, Oh My!Eric Palakovich Carr
 
Choosing a Javascript Framework
Choosing a Javascript FrameworkChoosing a Javascript Framework
Choosing a Javascript FrameworkAll Things Open
 
Virtual Madness @ Etsy
Virtual Madness @ EtsyVirtual Madness @ Etsy
Virtual Madness @ EtsyNishan Subedi
 

Similaire à Backbone.js Basics for Building JavaScript Apps (20)

Understanding backbonejs
Understanding backbonejsUnderstanding backbonejs
Understanding backbonejs
 
Aplicacoes dinamicas Rails com Backbone
Aplicacoes dinamicas Rails com BackboneAplicacoes dinamicas Rails com Backbone
Aplicacoes dinamicas Rails com Backbone
 
Backbone.js
Backbone.jsBackbone.js
Backbone.js
 
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
 
前端MVC 豆瓣说
前端MVC 豆瓣说前端MVC 豆瓣说
前端MVC 豆瓣说
 
Client-side MVC with Backbone.js (reloaded)
Client-side MVC with Backbone.js (reloaded)Client-side MVC with Backbone.js (reloaded)
Client-side MVC with Backbone.js (reloaded)
 
Clean Javascript
Clean JavascriptClean Javascript
Clean Javascript
 
Client-side MVC with Backbone.js
Client-side MVC with Backbone.js Client-side MVC with Backbone.js
Client-side MVC with Backbone.js
 
Backbone Basics with Examples
Backbone Basics with ExamplesBackbone Basics with Examples
Backbone Basics with Examples
 
Django class based views (Dutch Django meeting presentation)
Django class based views (Dutch Django meeting presentation)Django class based views (Dutch Django meeting presentation)
Django class based views (Dutch Django meeting presentation)
 
Backbonejs for beginners
Backbonejs for beginnersBackbonejs for beginners
Backbonejs for beginners
 
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
 
Javascript MVC & Backbone Tips & Tricks
Javascript MVC & Backbone Tips & TricksJavascript MVC & Backbone Tips & Tricks
Javascript MVC & Backbone Tips & Tricks
 
Django Class-based views (Slovenian)
Django Class-based views (Slovenian)Django Class-based views (Slovenian)
Django Class-based views (Slovenian)
 
laravel tricks in 50minutes
laravel tricks in 50minuteslaravel tricks in 50minutes
laravel tricks in 50minutes
 
Introducing CakeEntity
Introducing CakeEntityIntroducing CakeEntity
Introducing CakeEntity
 
jQuery Data Manipulate API - A source code dissecting journey
jQuery Data Manipulate API - A source code dissecting journeyjQuery Data Manipulate API - A source code dissecting journey
jQuery Data Manipulate API - A source code dissecting journey
 
Django Rest Framework and React and Redux, Oh My!
Django Rest Framework and React and Redux, Oh My!Django Rest Framework and React and Redux, Oh My!
Django Rest Framework and React and Redux, Oh My!
 
Choosing a Javascript Framework
Choosing a Javascript FrameworkChoosing a Javascript Framework
Choosing a Javascript Framework
 
Virtual Madness @ Etsy
Virtual Madness @ EtsyVirtual Madness @ Etsy
Virtual Madness @ Etsy
 

Dernier

Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxhariprasad279825
 
"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
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
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
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024The Digital Insurer
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
The Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfThe Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfSeasiaInfotech2
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Wonjun Hwang
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
Vector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesVector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesZilliz
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
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
 

Dernier (20)

Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptx
 
"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
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
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
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
The Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfThe Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdf
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
Vector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesVector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector Databases
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
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
 

Backbone.js Basics for Building JavaScript Apps

  • 1. Backbone.js Simple Tutorial by @fallroot
  • 2. Backbone.js Backbone supplies structure to JavaScript-heavy 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 application over a RESTful JSON interface.
  • 3. $ rails new todoapp Back-end $ cd todoapp $ rm public/index.html $ rails g scaffold todo title:string done:boolean • Ruby on Rails $ rake db:migrate • 3.1.0 RC5 $ rails s
  • 4. <script type="text/template"></script> Dependency <script src="jquery.js / zepto.js"></script> <script src="underscore.js"></script> <script src="backbone.js"></script> <script src="my-scripts.js"></script>
  • 5. var Item = Backbone.Model.extend({ urlRoot: '/todos' POST }); var item = new Item({ title: 'Create new todo' }); • Backbone.Model.extend(properties, item.save(); [classProperties]) • model.save([attributes], [options]) • model.url() • model.urlRoot • /urlRoot/id
  • 6. var Item = Backbone.Model.extend({ urlRoot: '/todos' PUT }); var item = new Item({ title: 'Create another todo' }); • _.bind(function, object, [*arguments]) item.save(); • _.delay(function, wait, [*arguments]) var save = _.bind(item.save, item); _.delay(save, 5000, {title: 'Title updated'});
  • 7. var Item = Backbone.Model.extend({ urlRoot: '/todos' DELETE }); var item = new Item({ title: 'This will be deleted' }); • model.destroy([options]) item.save(); _.delay(_.bind(item.destroy, item), 5000);
  • 8. var Item = Backbone.Model.extend({ urlRoot: '/todos' GET }); var ItemView = Backbone.View.extend({ tagName: 'li', initialize: function() { • Backbone.View.extend(properties, this.model.bind('change', this.render, this); [classProperties]) }, • model.fetch([options]) render: function() { this.el.innerHTML = this.model.get('title'); • model.get(attribute) return this; • object.bind(event, callback, [context]) } }); var item = new Item({id: 1}); item.fetch(); var itemView = new ItemView({model: item}); $('#todos').append(itemView.el);
  • 9. var Item = Backbone.Model.extend(); Collection var ItemView = Backbone.View.extend({ tagName: 'li', initialize: function() { this.model.bind('change', this.render, this); }, • Backbone.Collection.extend(properties, render: function() { [classProperties]) this.el.innerHTML = this.model.get('title'); return this; • collection.fetch([options]) } • collection.model }); • collection.url or collection.url()
  • 10. var Item = Backbone.Model.extend(); var List = Backbone.Collection.extend({ Collection var ItemView = Backbone.View.extend({ model: Item, tagName: 'li', url : '/todos' }); initialize: function() { var ListView = Backbone.View.extend({ this.model.bind('change', this.render, this); }, el: $('#todos'), • Backbone.Collection.extend(properties, initialize: function() { render: function() { this.collection.bind('reset', this.render, this); [classProperties]) this.el.innerHTML = this.model.get('title'); this.collection.fetch(); • collection.fetch([options]) return this; }, } • collection.model }); render: function() { var el = this.el; • collection.url or collection.url() this.collection.each(function(item) { var itemView = new ItemView({model: item}); el.append(itemView.render().el); }); return this; } }); new ListView({collection: new List});
  • 11. var Router = Backbone.Router.extend({ routes: { Router '*action': 'actionCallback' }, actionCallback: function(action) { document.body.innerHTML = action; } • Backbone.Router.extend(properties, }); [classProperties]) var router = new Router(); • router.navigate(fragment, [triggerRoute]) Backbone.history.start(); • Backbone.history.start([options]) router.navigate('started', true); • URL Fragment var navigate = _.bind(router.navigate, router); _.delay(navigate, 3000, 'moved', true); • history.pushState / popState • window.onhashchange • IE8 • polling if not supported
  • 12. <script type="text/template" id="item-template"> <p class="done"> Template <input type="checkbox" <% if (done) { %>checked<% } %>> </p> <p class="title"><%= title %></p> <p class="commands"> <button class="edit">Edit</button> <button class="remove">Remove</button> </p> • _.template(templateString, [context]) </script> • model.toJSON()
  • 13. <script type="text/template" id="item-template"> <p class="done"> var Item = Backbone.Model.extend({ Template <input type="checkbox" <% if (done) { %>checked<% } %>> urlRoot: '/todos' </p> }); <p class="title"><%= title %></p> <p class="commands"> var ItemView = Backbone.View.extend({ <button class="edit">Edit</button> tagName: 'li', <button class="remove">Remove</button> </p> template: _.template($('#item-template').html()), • _.template(templateString, [context]) </script> initialize: function() { • model.toJSON() this.model.bind('change', this.render, this); }, render: function() { this.el.innerHTML = this.template(this.model.toJSON()); return this; } }); var item = new Item({id: 1}); item.fetch(); var itemView = new ItemView({model: item}); $('#todos').append(itemView.el);
  • 15. Conclusion • For JavaScript Heavy Application • Single-Page Application • Skinny Back-end • RESTful JSON Interface

Notes de l'éditeur

  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