Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Namespace - Multiple Levels

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?

like image 892
Dismissile Avatar asked Oct 19 '11 16:10

Dismissile


2 Answers

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();
like image 197
JoshHetland Avatar answered Nov 01 '22 09:11

JoshHetland


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"
like image 4
David Harkness Avatar answered Nov 01 '22 08:11

David Harkness