James Magness

Living in the future

JavaScript Namespace Snippet

Coming back to JQuery and vanillajs after developing with YUI left me wanting to clean up a lot of code. I found I had no consistant Namespace patten. This has been lifted from the HTML5 mobile boilerplate.

/**
 * 2012-11-28 - JRM
 * Simple namespace pattern
 * Seen all over and lifted from HTML5 Mobile Boilerplate
 * https://github.com/h5bp/mobile-boilerplate/blob/master/js/helper.js
 */

(function(document) {

    window.NS = window.NS || {};

    NS.resultNode = document.getElementById('result');

    NS.fn1 = function () {
        NS.resultNode.innerHTML = "Hello Namespace";
    };

})(document);

NS.fn1();