Skip to content

Instantly share code, notes, and snippets.

@timhudson
Last active December 14, 2015 07:59
Show Gist options
  • Save timhudson/5054881 to your computer and use it in GitHub Desktop.
Save timhudson/5054881 to your computer and use it in GitHub Desktop.

Here is an example of using some helper methods to help manage boilerplate view code. This baseInitialize helper basically wraps the existing initialize method and runs some boilerplate code first.

// Global helper object
var helpers = {
  
  // Example helper
  // This method will wrap any existing initialize method
  // and run some boilerplate first
  baseInitialize: function(view) {
    (function() {
      
      // Store reference to existing initialize
      var _initialize = this.initialize;
      
      // Replace initialize method
      this.initialize = function() {
        // Bind all view methods to view
        _.bindAll(this);
        
        // Run existing initialize
        _initialize()
      }
    }).apply(view);
  } 
}

var SomeView = Backbone.View.extend({
  initialize: function() {
    // This will run after _.bindAll(view)
  }
});

helpers.baseInitialize(SomeView)

Now, in this instance, using a version of the module pattern seems a bit overkill. We don't need any sudo-private variables and we really have no need to worry about methods being overridden. A more succint version might look like this:

var helpers = {

  baseInitialize: function(view) {
    var _initialize = view.initialize;
    
    view.initialize = function() {
      _.bindAll(view);
      _initialize()
    }
  } 
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment