I have confusion on how to proceed with my project. I am developing an enterprise app in which lots of modules are to be written. Most of module will be using lots of jQuery plugins to create complex grids, draw graphs for different purposes which means modules will be appending divs, tables etc a lot to DOM.
I want to preserver namespace since this will be large app. For that I came across prototype method and self-executing anonymous function. self-executing anonymous function seems to be recommended a lot.
My questions are
My Project Scope:
Kindly help me understand this self executing thing in my project scope, which is My project Holds a main namespace say "Myapp" and and its modules like Myapp.moduleA, Myapp.moduleB.MyApp will trigger its modules on click etc. What is best way to go for me ?
Self-Executing Anonymous Func
(function( skillet, $, undefined ) {
//Private Property
var isHot = true;
//Public Property
skillet.somevar = "Bacon Strips";
//Public Method
skillet.draw = function() {
//Draw a grid
};
//Private Method
function _grid( ) {
//
}
}
}( window.skillet = window.skillet || {}, jQuery ));
You cannot reuse a self executing function, it just executes immediately and that's it.
If you need to execute it multiple times, you should just declare a function.
A possible approach is this:
var MYNAMESPACE.Object = (function(){
// private methods
var somemethod = function(){};
// public methods
return {
somepublicmethod: function(){}
};
})();
Now you can call it like this:
MYNAMESPACE.Object.somepublicmethod();
As for executing upon startup. Provided you only create methods and don't DO anything immediately inside your declaration, it won't affect performance too much unless you have a really big amount of modules. If that's the case, you should probably look into the asynchronous module loader pattern (AMD). RequireJS is a good example of that: http://requirejs.org
I wrote an article about JS namespaces which could be interesting for you:
http://www.kenneth-truyers.net/2013/04/27/javascript-namespaces-and-modules/
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