Breaking my js into smaller bits

My JavaScript file now has a length of more than 1000 lines. I need to make it more manageable. Here is the basic structure of my file:

// Some settings (easily put in a separate file) // Some jQuery plugins (easily put in a separate file) $(function () { var gadget1 = (function() { var private, public; // stuff return public; }()); var gadget2 = (function() { // gadget2 uses gadget1 var private, public; // stuff return public; }()); var gadget3 = (function() { // gadget3 uses gadget1 and gadget2 var private, public; // stuff return public; }()); // Playing around with the gadgets. }); 

The bulk of my code is enclosed in $(document).ready() and consists of "gadgets" that are short circuits. How can I separate each "gadget" in a separate module?

+4
source share
3 answers

You can use the namespacing template

 MyAPP = {} MyAPP.Gadget1 = (function () { //blah blah })() 

and then auxiliary

 MyAPP.helpers = (function () { //here are my helper functions/properties etc. })() 

These objects with names will be in separate files.

+7
source

A simple solution is to process the creation of each gadget in a separate file, one file for each gadget. Just include the files in the correct order and make the gadgets global (by defining them on the window ).

The best solution would be to create function definitions (define somehow somehow) for each gadget. The gadget constructor will accept its dependencies. If you define each type of gadget in your own file, you can simply create them in the ready() call. The advantage of this approach is that you need to create more gadgets of any type, you can do this because you defined them as your own functions.

0
source

Another option is to get to know make

Separate each of the files and create an assembly script that combines them all together.

0
source

All Articles