The idea to get this rolling is following:
- Define an initialiser module
- Define your other modules that require this module
- Load all your modules inside your main.js
- Run the initialiser module, thus searching for which of your modules need to be initialised
This is the engine of the entire system, we declare two private arrays which store the names of the possible modules we are loading and a reference to the class.
We expose three public methods via an object literal, I want this to be a singleton as maintaining state on the arrays is important:
- init - Which loops over the arrays and finds if the data-attr is there on the page to be initialised. Also gets the data-options attribute to pass in options to the class that is to be initialised.
- runModuleTasks - This method runs for each item that is part of the jQuery object that matches its data-attr for that particular module.
- register - To be used run in each of your modules, will push the relevant data to the private arrays.
This is a standard module that you accepts to parameters:
- The element that has the data-attr that initialises the module
- Any options you pass in using the data-options attribute
To successfully run the modules the actual HTML elements on the page only need one thing - Have the correct data-attr. In the modules you specify a name for that module and that is what you have to call to run the module through the data-attr. In the example above I am demonstrating the module “spring”, so to initialise this you need to apply “data-spring” to the element.
Optionally we can apply a data-options attribute to the element to allow options to be passed in. The only requirement for the options is to specify them in valid JSON format, the modules will take care of the rest.