Thursday, April 16, 2009

YUI-Like Javascript Namespaces

I really like the idea of Javascript namespaces for projects that have a lot of javascript (or even a little javascript on a lot of pages). YUI has a really good implementation, so I took a look at how they did theirs and ripped out the namespace creation part so I could use it on any project I wanted without having to include the YUI library.

The biggest benefit to using namespaces is avoidance of collisions. When using namespaces, you can be sure that no 3rd-party library or other coder is overwriting your functions or properties. Also, you can also use a javascript compresser / combiner to combine a lot of JS files into 1 JS file in order to reduce the amount of requests you make to the server. If you use namespaces, you can be sure that when you put all of the JS files together, you won't have any collisions.

To use the code, first put the following code in a globl js file:

if (typeof YourSite == "undefined") {
   var YourSite = {};
}

YourSite.namespace = function() {
    var a = arguments, o = null, i, j, d;
    for (i = 0; i < a.length; i = i + 1) {
        d = a[i].split(".");
        o = window;
        for (j = 0; j < d.length; j = j + 1) {
            o[d[j]] = o[d[j]] || {};
            o = o[d[j]];
        }
    }
    return o;
};

Then for each page or section of your site you can create a namespace:
YourSite.namespace("YourSite.Section1");
Then when creating functions or properties, you can write:

YourSite.Section1.myProperty = "blah";

YourSite.Section1.myFunction = function(){
    alert(YourSite.Section1.myProperty);
}

YourSite.Section1.myFunction();


2 comments:

  1. I would prefer YourSite = window.YourSite || {}; over the typeof undefined conditional.

    ReplyDelete
  2. What's with the loop controls that have "i = i + 1"? How about i++?

    ReplyDelete