Javascript Module Template with jQuery

I am trying to understand the concept of plugins like jQuery with plugins. My goal is to split my modules into different files and properly initialize them after 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'm doing it now is to call MY_LIBRARY.init () inside the jquery function after I installed 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 independently call MY_LIBRARY and modules when dom is ready, without using:

 $(function(){ MY_LIBRARY.init(); }); 

Update

I worked on this while trying to reproduce the jquery way, so I made this piece of code . Instead of using '$', I use "X $" as my custom global object, so I can do something like:

 X$( 'MyModule1', { init: function(){}, doStuff: function(){} }); 

or

 X$('MyModule1').doStuff(); 

I think this template works for me. At the moment, the only thing I could not reproduce was to use something like:

 X$.core.myCoreFunction() { return true; }; // plugin function yay! X$.myCoreFunction(); // alerts X$.myCoreFunction is not a function 

Which kind of weird as jQuery does it with plugins. Any thoughts on this?

+4
source share
1 answer

I would try to use a function wrapper around the definitions of your module, especially since you might find that there is a lot of commonality between your modules besides the init function.

For example, here I define a lib function that helps you declare a new library and automatically binds the init function to document.ready :

 function lib(module) { $(function() { if (module.init) { module.init(); } }); return module; } var MYLIB = lib(function() { return { init: function() { // ... } }; }()); 

You can use another option for one template, but this will not allow you to add a lot of additional code and will allow you to manage all your libraries the same way. For example, you could also return the dummy object to the lib when it was called initially, and after document.ready it uses the function passed to generate the real object, which will allow you to completely exclude explicit init

 function lib(moduleMaker) { var module = {}; $(function() { moduleMaker(module); }); return module; } var MYLIB = lib(function(mylib) { mylib.foo = function() {/*...*/}; // other init stuff, we've already waited for document.ready }); 
+2
source

Source: https://habr.com/ru/post/1338240/


All Articles