If you're a beginner learning JavaScript and jQuery for the first time, you are likely to right your code like this:
Typical jQuery code
1 2 3 4 5 6 7 8
$(document).ready(function() { $("#btn").click(function() { // you code here }); $("#btn2").click(function() { // you code here }); )};
There is nothing wrong with this. However, when your project gets more complex; you are going to need a way to organise events and function so that they can be maintained easily. This is what a modular pattern intends to solve. To give an example, I wrote a UserActions object which contains some user actions of a typical website.
UserActions object
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
//you may import utility Class here//var util = new CommonUtil();var UserActions = (function() { // regular variables and jquery variables here //var searchProviderGeneral = null, //providerListingEmpty = {}; return { /** * All the elements required before an * event occured must be in the init function. * * Bind functions contain event functions * and regular function with parameters. */ init: function() { // initialize regular variables and jquery variables from the top //searchProviderGeneral = $('#search-provider-name'); // good //providerListingEmpty = null; // call the event driven functions here this.bindUserActions(); }, bindUserActions: function() { // event here is click searchProviderGeneral.click(function() { // your code here }); // you can add function related to the event providerListingEmpty = function(value) { // your code here }; } }; // end return })();
UserActions is a module. This means any functions not related to user actions must not be written in this module. Thus, each module is specific for solving a problems or tasks and cannot be mix up with other module. To use a module just simply make a single JavaScript file to instantiate all the functions and jQuery variables.
app.js
1 2 3 4 5 6
//this is how to call the module or run the app $(document).ready(function() { // just call the module like this. UserActions.init(); ) };