Wednesday, 13 November 2013

Use closures to keep variable declarations short in Backbone View


This tip applies to JavaScript more broadly, and thus isn't limited to Backbone. We all know that letting variables slip up into the global scope is a Bad Thing. This is why it's important to declare all variables using the varkeyword at the top of each function. (Due to variable hoisting in JavaScript, variables defined anywhere in a function are hoisted to the top when it's executed, so always declare them at the top to avoid sad surprises). In complex functions, the list of local variables at the top can grow unruly. To keep variable declarations closer to where they're actually used in the code, use anonymous functions to give yourself an inline local scope:
myNamespace.myView = Backbone.View.extend({
  render: function() {
    var height = 110,
          width = 340,
          is_nested_row = false,
          // tons of other local variables
          render_footer = true;

      // time to format footer. keep local footer vars close to implementation
          (function() {
            var outer_height = 234,
                  background_color = red;

             $footer.height(outer_height).css('background', background_color);
          })();

  }
});

No comments:

Post a Comment