Monthly Archives: August 2011

Aliases with Google Closure

I’m starting to use the closure library and all of it. The closure compiler is nice because it can compress your JS code down, a LOT. In order to get the biggest bang for your buck. you want to use the advanced optimization settings. It can eliminate unused code, inline functions, and rename variables.

In order for variable renaming to work, you have to behave by closure’s rules. One rule closure has is: Let me do the optimization. One of the main reasons for this is that some shortcuts can make it hard to determine your intent.

One shortcut I like to use is to create alias to JavaScript objects that have long names or long namespaces.

(function() {
  var alias = a.very.long.namespace;
  /** @constructor */
  alias.NewClass = function() {};
})();

Now, to you are I, we can easily tell that I intend to use this self-calling anonymous function as a closure to store my alias; however, how can a compiler know that this was my intent.

Intent is a key concept when you work with the advanced compilation. In the above example, Closure knows that a.very.long.namespace.NewClass is even a class because of the constructor annotation. The way to tell Closure that you intend to make aliases is by using the goog.scope function1.

goog.require('goog.dom');
goog.require('goog.events');
goog.require('goog.events.EventType');

goog.scope(function() {
  var dom = goog.dom;
  var events = goog.events;
  var EventType = goog.events.EventType;

  var elem = dom.getElement('myElement');
  events.addEventListener(elem, EventType.CLICK, function() {
    alert('I was clicked');
  });
});

Continue reading