shadr.us

Building a JS Library

Javascript is a beautiful language when you used correctly. More and more, entire applications are being built primarily in Javascript. Getting started, though, is often the hardest part. This article will attempt to provide a starting point for building reusable javascript libraries.

Wrap Your Code

Right off the bat, it’s important to wrap all of your code:

(function () {
  /* All of your code goes in here! */
})();

Wrapping code in an anonymous function ensures that nothing is “leaked” into the global context. This may not seem so important at first, but as your app grows, it really is nice to know that you’re not “stepping” on yourself (or other libraries that you may be using).

Expose Functionality

Now, what if we want to actually expose some code to the surrounding page. For our example, let’s assume we’re developing for spicyjs.com, and our code is in the file spicy.js. We’ll create a single global variable named “SPICY”.

(function () {
  var spicy = {}
  window.SPICY = {};
  
  /* ... */

})();

Here’s another alternative:

var SPICY = (function () {
  var spicy = {}
  
  /* ... */
  
  return spicy;
})();

Now, anyone that wants to use our code outside of this file can through the “SPICY” variable. Internal to our library, we can refer to to this object as “spicy”. This sort of naming helps when dealing with multiple libraries that talk to one another. If you see your variable name in all lower case, you’ll know where you are.

As a general rule, it’s best to name all global variables in all CAPS just so you’ll recognize them easily.

To expose a function to the outside world, explicitly add it to the “SPICY” object.

(function () {
  var spicy = {}
  window.SPICY = SPICY;

  function button(spec) {
    // build a button
  }
  spicy.button = button;
  
  /* ... */
})();

When using this library, you’ll simply call your method through the SPICY variable.

SPICY.button({
  title: 'Click Me',
  action: function (event) {
    alert('I just got clicked, yo');
  }
});

References