8

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?

0

5 Answers 5

9

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();
Sign up to request clarification or add additional context in comments.

Comments

4

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"

Comments

2

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

x = {};
x.y = {};
x.y.z = function() {};

2 Comments

To be fair, these are commonly called "namespaces" in the JS community when they're used to organize code.
Sure. I'm just pointing out they're not real namespaces, they just look like them.
1

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();

Comments

1

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/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.