Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on Aug 19th, 2012  |  syntax: None  |  size: 1.82 KB  |  hits: 10  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. // This method gives you an easier way of calling super
  2. // when you're using Backbone in plain javascript.
  3. // It lets you avoid writing the constructor's name multiple
  4. // times. You still have to specify the name of the method.
  5. //
  6. // So instead of having to write:
  7. //
  8. //   User = Backbone.Model.extend({
  9. //     save: function(attrs) {
  10. //       this.beforeSave(attrs);
  11. //       return User.__super__.save.apply(this, arguments);
  12. //     }
  13. //   });
  14. //
  15. // You get to write:
  16. //
  17. //   User = Backbone.Model.extend({
  18. //     save: function(attrs) {
  19. //       this.beforeSave(attrs);
  20. //       return this._super("save", arguments);
  21. //     }
  22. //   });
  23. //
  24.  
  25. ;(function(Backbone) {
  26.  
  27.   // The super method takes two parameters: a method name
  28.   // and an array of arguments to pass to the overridden method.
  29.   // This is to optimize for the common case of passing 'arguments'.
  30.   function _super(methodName, args) {
  31.  
  32.     // Keep track of how far up the prototype chain we have traversed,
  33.     // in order to handle nested calls to _super.
  34.     this._superCallObjects || (this._superCallObjects = {});
  35.     var currentObject = this._superCallObjects[methodName] || this,
  36.         parentObject  = findSuper(methodName, currentObject);
  37.     this._superCallObjects[methodName] = parentObject;
  38.  
  39.     var result = parentObject[methodName].apply(this, args || []);
  40.     delete this._superCallObjects[methodName];
  41.     return result;
  42.   }
  43.  
  44.   // Find the next object up the prototype chain that has a
  45.   // different implementation of the method.
  46.   function findSuper(methodName, childObject) {
  47.     var object = childObject;
  48.     while (object[methodName] === childObject[methodName]) {
  49.       object = object.constructor.__super__;
  50.     }
  51.     return object;
  52.   }
  53.  
  54.   _.each(["Model", "Collection", "View", "Router"], function(klass) {
  55.     Backbone[klass].prototype._super = _super;
  56.   });
  57.  
  58. })(Backbone);