I am starting up a new project and I am reviewing my best-practices to try to prevent any problems, and also to see what bad habits I have gotten into.
I am not terr
I personally have a different coding style to that. This is one of them. The other is basically an imitation of the style used in backbone.js
var myProgram = (function() {
var someGlobal, someGlobal2;
var subModule1 = (function() {
...
var init = function() {
};
...
init();
return {
"someMethod": someMethod,
...
};
}());
var OtherSubModule = (function() {
...
var init = function(param) { ... };
...
return {
"init": init,
...
};
}());
var init = function(param) {
...
OtherSubModule.init({
"foo": param.foo,
"bar": param.bar,
...
});
};
return {
"init": init,
"somePublic": OtherSubModule.foobar,
...
}
}());
Depends whether I need to supply a public API to other users, which backbone does a lot better. I prefer to make modules driven by an init
function for initial configuration and for the rest completely event driven.
[Edit]
Given the edited question I have a different pattern for this. Each file defines a function on some object in my case it was $.FooBar.plugins
(function() {
var foo = function() { ... };
var bar = (function() { ... }());
myNamespace.plugins["MyPlugin"] = function() {
... do stuff
... bind to evevnts
};
}());
Then we use a boot strapper that was something like this :
(function() {
var needed = function() {
// Feature detection
};
var load = function() { ... };
var getOptions = function() {
// Call something on a page by page basis.
};
for (var plugin in pluginList) {
if (needed(plugin)) {
load(plugin, function() {
// get page specific options
var options = getOptions();
// run plugin
myNameSpace.plugins[plugin](options);
// If all have been loaded trigger ready handlers
if (pluginCurrentCount == pluginCount) {
readyTrigger();
}
});
pluginCount++;
}
}
// start loading plugins after all have been counted
load.startLoading();
var readyTrigger = function() {
// Run all ready handlers
}
// Implement your own DOM ready function to run when all plugins
// have loaded.
myNameSpace.ready = function(handler) {
if (isReady) {
handler();
} else {
readyList.push(handler);
}
};
}());
That's a lot of gaps and pseudo code but you should get the idea. If it's not obvouis feel to question it.
Then on the page we have something like this
<html>
<head>
<script type="text/javascript">
var pageSpecific = {
"pluginName": {
"cssClass": "foobar",
"submitOnEnter": false,
...
},
...
};
</script>
<script src="bootstrapper.js" />
...
</head>
<body>
...
</body>
</html>