Return to Snippet

Revision: 43316
at March 21, 2011 23:57 by coprolit


Initial Code
// creating 'namespace' - using domain name, reversed, as a single global name, e.g. example.com:

var org;
if (!org) 
    org = {};
else if (typeof org != "object")
    throw new Error ("org already exists and is not an object");
if (!org.example) 
    org.example = {};
else if (typeof org.example != "object")
    throw new Error ("org.example already exists and is not an object");


// creating object inside namespace:

org.example.Highlight = function() {
    // define private data and functions
    var highlightId = "x";
    function setHighlight(color) { 
        document.getElementById(highlightId).style.color = color;
    }
 
    // return public pointers to functions or properties
    // that are to be public
    return {
        goGreen: function() { setHighlight("green"); },
        goBlue : function() { setHighlight("blue"); }
    }
}(); //end closure definition and invoke it

//From any other module, these public methods could be invoked in either way as follows:

org.example.Highlight.goBlue();
 
var h = org.example.Highlight;
h.goGreen();

Initial URL
http://en.wikipedia.org/wiki/Unobtrusive_JavaScript

Initial Description
Unobtrusive JavaScript should add as little as possible to the global object or global namespace of the environment in which it runs.
With following solution each module-writer's code is contained in private or in a unique namespace and cannot interfere with or intrude upon any other code at any time.

Initial Title
using unobtrusive namespace

Initial Tags


Initial Language
JavaScript