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?
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();
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With