Deep Dive Into Backbone.js Internals +
Underscore.js.
Mauvis Ledford
CTO, Pathbrite
Backbone.js: Quick Facts

•  0.1.0 released Oct 13, 2010, latest stable 0.9.2 – 7 months ago
•  Used in dozens of popular web and mobile web sites out there:




•  Soundcloud, Stripe, Grooveshark, Do, BitTorrent, Nike+, …


2
Backbone.js: Source Code Analysis

Lines of code
•  1432 lines w/ comments.
•  856 lines without.


Size
•  52kb raw w/ comments
•  30k without
•  5.6kb packed and gzipped


Underscore
•  4kb packed and gzipped

3
Backbone.js: 856 line breakdown

•  Model (234)              inheritance,
                                2%
•  Collection (218)                             misc,
                         .sync, 3%
•  View (75)                                     8%
                                                             Model,
•  Router (46)                                                29%
•  History (116)                   History,
                                    15%
•  Event (65)
•  Sync (29)
                      Router, 6%
•  Inherit (17)                         View,           Collection,
•  Misc (55)                            10%               27%




4
How to build a good framework?
Starts with these 3.




5                      Taken from the PunyMCE framework.
Same three functions in other libraries

jQuery
•  jQuery.each
•  jQuery.extend
•  jQuery.isFunction, jQuery.isArray, jQuery.isEmptyObject, jQuery.isNumeric


Underscore
•  _.each
•  _.extend
•  _.isFunction, _.isArray, _.isEmpty, _.has, _.isEqual




6
_.extend({},{},…)
Backbone source uses this heavily.




7
Diving into the code: top down
Environment setup.
                                            Anonymous function
                                               to encapsulate
                                             framework setup.
                                                      	
  




       Calling anonymous
    function in the context of
             global object.
    Node:	
  global	
  DOM:	
  window	
  
8
Diving into the code: top down
Two checks: “exports” and “require”.
                                                           Preparing for jQuery-
…	
                                                          like “noConflict”
                                                                     	
  


                                                              Checks for existence of
                                                            global “exports” variable. If
                                                              exists, assume we are
                                                                    serverside. 	
  




…	
  
                                   Similarily, if underscore isn’t loaded and global
                                      “require” exists include underscore lib.
                                                            	
  
9       Let your knowledge shine
Diving into the code: top down                Supports jQuery,
NoConflict and optional DOM library.          Zepto, or Ender	
  

…	
  



                                                          Allows you to
                                                        restore Backbone
                                                          namespace to
                                                       previous Backbone.	
  




…	
  
        Used with Backbone.sync method.	
  


10
Diving into the code: top down
Event class, so important!
…	
  
                                                   All of Backbone’s
                                                  classes inherit this
                                                    class and now
                                                       have these
                                                        methods.	
  




…	
  
                    Backwards compatibility	
  
11
Diving into the code: top down
Mixing Event class in to custom class.

…	
  




…	
  




12
Diving into the code: top down
Model class
…	
  




                             Every new model gets a unique id.	
  


                                  Attributes are set silently on
                                         model creation.
                                                	
  
                                 Last step, call the models init.
                                                 	
  
…	
  
13
Diving into the code: top down
Model class

…	
  


                                Notice that `Events` class
                             extends `Model.prototype` which
                                  is then extended by an
                                    anonymous object.	
  




…	
  
14
Diving into the code: top down
Collection class
                             If `comparator` function is passed
                              new models are sorted in order.	
  
…	
  




…	
  




15
Diving into the code: top down
Collection class
…	
  

                                 Notice that `Events` class is
                                       mixed in again.	
  




                                          Additional underscore
                                           methods are added
                                                directly to
                                          `Collection.prototype`.	
  
…	
  
16
Diving into the code: top down
Demonstrating models and collections on https://pathbrite.com/portfolios
.
    // Count portfolios
    rrripple.data.portfolios.length;

    // Get collection JSON list.
    rrripple.data.portfolios.toJSON();

    // Get model JSON list.
    rrripple.data.portfolios.first().toJSON();

    // Add new portfolio item.
    rrripple.data.portfolios.add({
        title : 'Watermelon'
    });




17
Diving into the code: top down
Router class.

…	
  




…	
  

  Show	
  sample	
  routes.	
  

18
Diving into the code: top down
History class

…	
  




…	
  
 Backbone.history.navigate('/portfolios', {
     trigger: true
 });

19
Diving into the code: top down
View class

…	
  
                                                                 `ensureElement` sets
                                                              `this.el` to a detached div if
                                                              no el or tagName specified.	
  



                                                          Arguments passed with these
                                                          keys are applied directly to the
                                                              instantiated view during
                                                           `this._configure`, the rest can
                                                             be found in `view.options`.	
  
…	
  
     Show:	
  rp.classes.views.popup	
  in	
  editor.	
  
     var	
  view	
  =	
  new	
  rrripple.classes.views.par>als.Se?ngsPopup();	
  
20
Diving into the code: top down
Inherits functionality
…	
  




                 User.prototype.save = function(attrs) {
                     // modify attrs code
                     User.__super__.save.apply(this, arguments);
                 };


                                    Shh! Saved referenced to parents
                                       prototype. Let’s you access
                                     parents method you could have
                                         overwritten on the child.	
  
…	
  
21
Diving into the code: top down
Giving all classes extend ability




…	
  




…	
  
                 Notice `_.extend` != `Collection.extend`!!!	
  




22
Live Demos
Frontend and backend Backbone examples

                                                    Pathbrite:	
  Backbone	
  as	
  
                                                    a	
  frontend	
  plaGorm.	
  
                                                    	
  
                                                    pathbrite.com	
  




     Kbot:	
  Turntable	
  robot	
  built	
  	
  
        on	
  Node	
  and	
  Backbone.	
  
                                          	
  
 github.com/krunkosaurus/kbot	
  
                                          	
  
23                                        	
  
Thanks!

Feedback?
mauvis@pathbrite.com
@krunkosaurus




24
Last year: Don’t Break the Chain
Sample responsive Backbone app.




                        hKp://dontbreak.me/	
  
                                 	
  
25

Deep Dive into Backbone.js Internals + Underscore.js

  • 1.
    Deep Dive IntoBackbone.js Internals + Underscore.js. Mauvis Ledford CTO, Pathbrite
  • 2.
    Backbone.js: Quick Facts • 0.1.0 released Oct 13, 2010, latest stable 0.9.2 – 7 months ago •  Used in dozens of popular web and mobile web sites out there: •  Soundcloud, Stripe, Grooveshark, Do, BitTorrent, Nike+, … 2
  • 3.
    Backbone.js: Source CodeAnalysis Lines of code •  1432 lines w/ comments. •  856 lines without. Size •  52kb raw w/ comments •  30k without •  5.6kb packed and gzipped Underscore •  4kb packed and gzipped 3
  • 4.
    Backbone.js: 856 linebreakdown •  Model (234) inheritance, 2% •  Collection (218) misc, .sync, 3% •  View (75) 8% Model, •  Router (46) 29% •  History (116) History, 15% •  Event (65) •  Sync (29) Router, 6% •  Inherit (17) View, Collection, •  Misc (55) 10% 27% 4
  • 5.
    How to builda good framework? Starts with these 3. 5 Taken from the PunyMCE framework.
  • 6.
    Same three functionsin other libraries jQuery •  jQuery.each •  jQuery.extend •  jQuery.isFunction, jQuery.isArray, jQuery.isEmptyObject, jQuery.isNumeric Underscore •  _.each •  _.extend •  _.isFunction, _.isArray, _.isEmpty, _.has, _.isEqual 6
  • 7.
  • 8.
    Diving into thecode: top down Environment setup. Anonymous function to encapsulate framework setup.   Calling anonymous function in the context of global object. Node:  global  DOM:  window   8
  • 9.
    Diving into thecode: top down Two checks: “exports” and “require”. Preparing for jQuery- …   like “noConflict”   Checks for existence of global “exports” variable. If exists, assume we are serverside.   …   Similarily, if underscore isn’t loaded and global “require” exists include underscore lib.   9 Let your knowledge shine
  • 10.
    Diving into thecode: top down Supports jQuery, NoConflict and optional DOM library. Zepto, or Ender   …   Allows you to restore Backbone namespace to previous Backbone.   …   Used with Backbone.sync method.   10
  • 11.
    Diving into thecode: top down Event class, so important! …   All of Backbone’s classes inherit this class and now have these methods.   …   Backwards compatibility   11
  • 12.
    Diving into thecode: top down Mixing Event class in to custom class. …   …   12
  • 13.
    Diving into thecode: top down Model class …   Every new model gets a unique id.   Attributes are set silently on model creation.   Last step, call the models init.   …   13
  • 14.
    Diving into thecode: top down Model class …   Notice that `Events` class extends `Model.prototype` which is then extended by an anonymous object.   …   14
  • 15.
    Diving into thecode: top down Collection class If `comparator` function is passed new models are sorted in order.   …   …   15
  • 16.
    Diving into thecode: top down Collection class …   Notice that `Events` class is mixed in again.   Additional underscore methods are added directly to `Collection.prototype`.   …   16
  • 17.
    Diving into thecode: top down Demonstrating models and collections on https://pathbrite.com/portfolios . // Count portfolios rrripple.data.portfolios.length; // Get collection JSON list. rrripple.data.portfolios.toJSON(); // Get model JSON list. rrripple.data.portfolios.first().toJSON(); // Add new portfolio item. rrripple.data.portfolios.add({ title : 'Watermelon' }); 17
  • 18.
    Diving into thecode: top down Router class. …   …   Show  sample  routes.   18
  • 19.
    Diving into thecode: top down History class …   …   Backbone.history.navigate('/portfolios', { trigger: true }); 19
  • 20.
    Diving into thecode: top down View class …   `ensureElement` sets `this.el` to a detached div if no el or tagName specified.   Arguments passed with these keys are applied directly to the instantiated view during `this._configure`, the rest can be found in `view.options`.   …   Show:  rp.classes.views.popup  in  editor.   var  view  =  new  rrripple.classes.views.par>als.Se?ngsPopup();   20
  • 21.
    Diving into thecode: top down Inherits functionality …   User.prototype.save = function(attrs) { // modify attrs code User.__super__.save.apply(this, arguments); }; Shh! Saved referenced to parents prototype. Let’s you access parents method you could have overwritten on the child.   …   21
  • 22.
    Diving into thecode: top down Giving all classes extend ability …   …   Notice `_.extend` != `Collection.extend`!!!   22
  • 23.
    Live Demos Frontend andbackend Backbone examples Pathbrite:  Backbone  as   a  frontend  plaGorm.     pathbrite.com   Kbot:  Turntable  robot  built     on  Node  and  Backbone.     github.com/krunkosaurus/kbot     23  
  • 24.
  • 25.
    Last year: Don’tBreak the Chain Sample responsive Backbone app. hKp://dontbreak.me/     25