Javascript Namespace - Multiple Levels

4k views Asked by At

I'm currently doing the following to give my javascript code a namespace:

(function(foo, $, undefined) {
    // function: showNoteDialog
    foo.showNoteDialog = function() {
       // ...
    }
}(window.foo = window.foo || {}, jQuery));

What I would prefer is instead of:

foo.showNoteDialog()

Is to have a multiple level namespace:

foo.notes.showDialog()
foo.other.showDialog()

Is this possible? How would I do this?

5

There are 5 answers

2
Vala On BEST ANSWER

There aren't namespaces in JS, but you can assign objects to other objects like

x = {};
x.y = {};
x.y.z = function() {};
0
JoshHetland On

Here is how i normally do it:

var TopLevel = TopLevel || {}; //Exentd or Create top level namespace
TopLevel.FirstChild = TopLevel.FirstChild || {}; //Extend or Create a nested name inside TopLevel

Using this method allows for safety between files. If TopLevel already exists you will assign it to the TopLevel variable, if it does not you will create an empty object which can be extended.

So assuming you want to create an application that exists within the Application namespace and is extended in multiple files you would want files that look like so:

File 1 (library):

var Application = Application || {};

Application.CoreFunctionality = Application.CoreFunctionality || {};
Application.CoreFunctionality.Function1 = function(){
  //this is a function
}//Function1

File 2 (library):

var Application = Application || {};

Application.OtherFunctionality = Application.OtherFunctionality || {};
Application.OtherFunctionality.Function1 = function(){
  //this is a function that will not conflict with the first
}

File 3 (worker):

//call the functions (note you could also check for their existence first here)
Application.CoreFunctionality.Function1();
Application.OtherFunctionality.Function1();
0
David Harkness On

Take a look at namespace.js. It allows you to declare nested namespaces with public and private methods. It's nice because it allows you to call any method inside the namespace block without a prefix--regardless of scope.

(function() {
  namespace("example.foo", bar);

  function foobar() { return "foobar"; };
  function bar() { return foobar(); };
}());

example.foo.bar(); // -> "foobar"
0
stamat On

Automating multilevel namespaces declaration in javascript is very simple as you can see:

var namespace = function(str, root) {
    var chunks = str.split('.');
    if(!root)
        root = window;
    var current = root;
    for(var i = 0; i < chunks.length; i++) {
        if (!current.hasOwnProperty(chunks[i]))
            current[chunks[i]] = {};
        current = current[chunks[i]];
    }
    return current;
};

// ----- USAGE ------

namespace('ivar.util.array');

ivar.util.array.foo = 'bar';
alert(ivar.util.array.foo);

namespace('string', ivar.util);

ivar.util.string.foo = 'baz';
alert(ivar.util.string.foo); 

Try it out: http://jsfiddle.net/stamat/Kb5xY/ Blog post: http://stamat.wordpress.com/2013/04/12/javascript-elegant-namespace-declaration/

0
Tengiz On

I do it using bob.js framework:

bob.ns.setNs('myApp.myMethods', {
    method1: function() {
        console.log('This is method 1');
    },

    method2: function() {
        console.log('This is method 2');
    }
});
//call method1.
myApp.myMethods.method1();
//call method2.
myApp.myMethods.method2();