SlideShare a Scribd company logo
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 Simple Tutorial

More Related Content

PPT
Propel sfugmd
PDF
Drupal 8: Fields reborn
PDF
Any tutor
PDF
50 Laravel Tricks in 50 Minutes
KEY
Theme API
PDF
Simplifying JavaScript Projects with ReactJS
PDF
Doctrine 2
PDF
Functionality Focused Code Organization
Propel sfugmd
Drupal 8: Fields reborn
Any tutor
50 Laravel Tricks in 50 Minutes
Theme API
Simplifying JavaScript Projects with ReactJS
Doctrine 2
Functionality Focused Code Organization

What's hot (20)

PDF
Be lazy, be ESI: HTTP caching and Symfony2 @ PHPDay 2011 05-13-2011
PDF
Nickolay Shmalenuk.Render api eng.DrupalCamp Kyiv 2011
PDF
Be RESTful (Symfony Camp 2008)
PDF
Building Smart Async Functions For Mobile
PPTX
WordPress plugin #3
KEY
Jquery Fundamentals
PDF
jQuery Rescue Adventure
PPTX
AngularJS Services
PDF
[Srijan Wednesday Webinars] Ruling Drupal 8 with #d8rules
PPTX
AngularJS - $http & $resource Services
PDF
Viastudy ef core_cheat_sheet
PDF
Drupal - dbtng 25th Anniversary Edition
KEY
jQuery Namespace Pattern
PPTX
jQuery Presentasion
PDF
Upgrade your javascript to drupal 8
PDF
I os 04
PPTX
AngularJS $Provide Service
KEY
JavaScript in Drupal 7: What developers need to know
PPT
Backbone js
PDF
Beyond the DOM: Sane Structure for JS Apps
Be lazy, be ESI: HTTP caching and Symfony2 @ PHPDay 2011 05-13-2011
Nickolay Shmalenuk.Render api eng.DrupalCamp Kyiv 2011
Be RESTful (Symfony Camp 2008)
Building Smart Async Functions For Mobile
WordPress plugin #3
Jquery Fundamentals
jQuery Rescue Adventure
AngularJS Services
[Srijan Wednesday Webinars] Ruling Drupal 8 with #d8rules
AngularJS - $http & $resource Services
Viastudy ef core_cheat_sheet
Drupal - dbtng 25th Anniversary Edition
jQuery Namespace Pattern
jQuery Presentasion
Upgrade your javascript to drupal 8
I os 04
AngularJS $Provide Service
JavaScript in Drupal 7: What developers need to know
Backbone js
Beyond the DOM: Sane Structure for JS Apps
Ad

Similar to Backbone.js Simple Tutorial (20)

PDF
Understanding backbonejs
PDF
Aplicacoes dinamicas Rails com Backbone
KEY
Backbone.js
PPTX
Taming that client side mess with Backbone.js
PDF
前端MVC 豆瓣说
PDF
Client-side MVC with Backbone.js (reloaded)
PDF
Clean Javascript
PDF
Client-side MVC with Backbone.js
PDF
Backbone Basics with Examples
KEY
Django class based views (Dutch Django meeting presentation)
PPTX
Backbonejs for beginners
PDF
Backbone.js — Introduction to client-side JavaScript MVC
PDF
Javascript MVC & Backbone Tips & Tricks
PDF
Django Class-based views (Slovenian)
PDF
laravel tricks in 50minutes
KEY
Introducing CakeEntity
PPTX
jQuery Data Manipulate API - A source code dissecting journey
PDF
Django Rest Framework and React and Redux, Oh My!
PDF
Choosing a Javascript Framework
PDF
Virtual Madness @ Etsy
Understanding backbonejs
Aplicacoes dinamicas Rails com Backbone
Backbone.js
Taming that client side mess with Backbone.js
前端MVC 豆瓣说
Client-side MVC with Backbone.js (reloaded)
Clean Javascript
Client-side MVC with Backbone.js
Backbone Basics with Examples
Django class based views (Dutch Django meeting presentation)
Backbonejs for beginners
Backbone.js — Introduction to client-side JavaScript MVC
Javascript MVC & Backbone Tips & Tricks
Django Class-based views (Slovenian)
laravel tricks in 50minutes
Introducing CakeEntity
jQuery Data Manipulate API - A source code dissecting journey
Django Rest Framework and React and Redux, Oh My!
Choosing a Javascript Framework
Virtual Madness @ Etsy
Ad

Recently uploaded (20)

PDF
Encapsulation_ Review paper, used for researhc scholars
PDF
gpt5_lecture_notes_comprehensive_20250812015547.pdf
PDF
Network Security Unit 5.pdf for BCA BBA.
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PDF
Assigned Numbers - 2025 - Bluetooth® Document
PDF
Machine learning based COVID-19 study performance prediction
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PPTX
Programs and apps: productivity, graphics, security and other tools
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PPTX
Machine Learning_overview_presentation.pptx
PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
PDF
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
DOCX
The AUB Centre for AI in Media Proposal.docx
PDF
Electronic commerce courselecture one. Pdf
PDF
Encapsulation theory and applications.pdf
PDF
Review of recent advances in non-invasive hemoglobin estimation
PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
Encapsulation_ Review paper, used for researhc scholars
gpt5_lecture_notes_comprehensive_20250812015547.pdf
Network Security Unit 5.pdf for BCA BBA.
Advanced methodologies resolving dimensionality complications for autism neur...
Assigned Numbers - 2025 - Bluetooth® Document
Machine learning based COVID-19 study performance prediction
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
Programs and apps: productivity, graphics, security and other tools
The Rise and Fall of 3GPP – Time for a Sabbatical?
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
Machine Learning_overview_presentation.pptx
“AI and Expert System Decision Support & Business Intelligence Systems”
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
The AUB Centre for AI in Media Proposal.docx
Electronic commerce courselecture one. Pdf
Encapsulation theory and applications.pdf
Review of recent advances in non-invasive hemoglobin estimation
Mobile App Security Testing_ A Comprehensive Guide.pdf
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf

Backbone.js Simple Tutorial

  • 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

Editor's Notes