practices posts

My Javascript Practices

It has been quite some time since I’ve posted anything, but I certainly haven’t stopped building websites. One thing I like to find out from other developers is how they do things so I can compare them with what I do and take anything that I like of theirs better, so I’m going to share some of my current practices. I’ll start with javascript, since I just built a javascript heavy site and want to share some more specific javascript stuff in later posts.

Base Library

To begin with, I use a namespace to store all of my javascript variables/objects in. This doesn’t pollute the “global” window object with many variables and drastically reduces the possibility of collisions with other libraries. Since javascript has no actual namespaces, but it does allow for generic objects and the ability to add arbitrary attributes and functions to them, I just create an object and add everything to it. I use __ because it is small and quick to type, can’t really be given any meaning based on the name, and probably won’t be used by someone else.

The only other thing I put in the global namespace is the base object type I instantiate that variable with. I did this as an object so I could conceivably create multiple instances and so that I could declare it later in the file and have all of the site specific code at the top. I call it tmlib since it is my library. So a bare instantiation might look like this:

if(typeof __ === 'undefined') var __ = new tmlib;
__.cfg.whatever = "whatever";
__.scrOnload = function(){
    doSiteSpecificSomething();
}
/*----------
©tmlib
---------*/
function tmlib(){
        this.classes = {};
        this.lib = {};
        this.cfg = {};
    }
    tmlib.prototype.addListeners = function(argElements, argEvent, argFunction, argBubble){
        var fncBubble = (argBubble)?argBubble : false;
        if(!__.lib.isArray(argElements)) argElements = new Array(argElements);
        for(var i = 0; i < argElements.length; ++i){
            var forElement = argElements[i];
            if(forElement.attachEvent)
                forElement.attachEvent("on"+argEvent, argFunction);
            else
                forElement.addEventListener(argEvent, argFunction, fncBubble);
        }
    }
/*--init */
__.addListeners(window, "load", __.scrOnload, false);
Continue reading post "My Javascript Practices"