I'm looking for a way to have a common.js, if you will, containing some functions to be used in other js scripts further down the hierarchy.
Usually I do this, simply by declaring a function like so: function x(){...}
to be called later on from some other js. However I ran in to some trouble with this approach when I tried to parse and mash all my .js files with Uglifyjs. After some research I've learned some advantages with the use of javascript modules
to solve my uglify problem as well as strive towards best practice.
I found a pretty neat solution using modules here:
Javascript : Best way to declare functions to be used globally?
The code fitted to my needs:
The modules section isn't properly defined ... here's a slightly tidied up example.
window.MainModule = (function($, win, doc, undefined) {
var modules = {};
// -- Create as many modules as you need ...
modules["alerter"] = (function(x,y){
var someFunction = function(){ alert(xy); };
return {
init: someFunction
};
}());
modules["alerter2"] = (function(){
var someFunction = function(){ alert('I alert second'); };
return {
init: someFunction
};
}());
return {
init: function(key){
modules[key].init();
}
};
}(jQuery, this, document));
$(window.MainModule.init['alerter']);
The problem I need help with is that I want to init module['alerter']
and provide the arguments to the function
modules["alerter"] = (function(x,y){
var someFunction = function(){ alert(xy); };
return {
init: someFunction
};
}());
by the use of$(window.MainModule.init['alerter'])
.
I've tried to be specific in an area thats rather new to me. Of course I'm grateful for your help.