I'm trying to grasp the concept of pluggable modules, like jQuery does with plugins. My goal is to split my modules into different files and initiliaze them properly after the DOM is ready according to jQuery.
Example
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="my_library.js"></script>
<script type="text/javascript" src="modules.js"></script>
<!-- Could be more -->
The way I am doing it right now is by calling MY_LIBRARY.init() inside a jQuery function after I set my modules.
// my_library.js
var MY_LIBRARY = {
init: function() {
var _self = this,
modules = _self.modules;
if (modules) {
for (var i in modules){
modules[i].init();
}
}
},
modules: {}
}
// modules.js
MY_LIBRARY.modules.MyModule1 = {
init: function(){
// initialize stuff
return this;
}
};
MY_LIBRARY.modules.MyModule2 = {
init: function(){
// initialize stuff
return this;
}
};
$(function(){
MY_LIBRARY.init();
});
The question is how can I self-invoke MY_LIBRARY and the modules when the DIM is ready, without using:
$(function(){
MY_LIBRARY.init();
});
Update
I've been working on this, trying to replicate the way jQuery does this, so I've written some code that uses 'X$' instead of '$' as my custom global object which allows me to do something like:
X$( 'MyModule1', { init: function(){}, doStuff: function(){} });
or
X$('MyModule1').doStuff();
I think this pattern works for me. At the moment, the only thing I couldn't replicate is using something like:
X$.core.myCoreFunction() { return true; }; // plugin function yay!
X$.myCoreFunction(); // alerts X$.myCoreFunction is not a function
Which is kind of weird since jQuery does this with plugins. Any thoughts on this one?