The JavaScript Module Pattern Used With jQuery

Introduction

I have always been primarily a backend developer, I love OOP, and try my best to follow all the best principles such as Encapsulation, Polymorphism, Separation of Concerns, and even the Law of Demeter when I design and write software. As such, I have fought tooth and nail to avoid writing in-browser apps. I have nothing against them, I believe that’s where the View needs to be... philosophically. I just want someone else to do it, to deal with the JavaScript and CSS because it’s so hard to discipline ourselves to write good, clean code. OOP code in the browser with JavaScript ES5 isn't difficult to write correctly, it’s just easy not to. (In future articles, I’ll discuss how I’ve overcome this with Angular 2, Typescript, and even ES6 features)

Background

Here we introduce the Module Pattern, this gives us a way in JavaScript to introduce private variables and functions, exposing only those parts we need to the outside world. There are several flavors of this available, you can implement it as a JavaScript object, you can use prototypes, or you can write it as an IIFE a JavaScript Immediately Invoked Function Expression. To do this, we implement a JavaScript Closure. More about closures here.


Using the Code

Enjoy the sample, and remember, it’s just a sample as each case may call for something a little different. For example, I’ve separated Init() and showMessage() functionality which in many cases can be combined.

Note: This code is not designed to be functional but to be used as a template.
  1. // <a href="http://slnzero.com" target="_blank">Solution Zero, Inc. Lubbock Texas</a>   
  2. /// Troy Locke -- <a href="mailto:troy@slnzero.com" target="_blank">[email protected]</a>  
  3.    
  4. var myMessageApp = (function() {  
  5.     "use strict"  
  6.    
  7.     // I avoid these with the bindControls functionality but I show if for example.  
  8.     var someElement = $("#foo"); // some element I know I'll use lots  
  9.    
  10.     // private variables  
  11.     var pvtMessageVal;  
  12.     var pvtAdditionalMessageVal;  
  13.       
  14.     // we create an object to hold all the jQuery controls, so we can call  
  15.     // binding after loading an HTML page dynamically via AJAX  
  16.     // see bindControls further down  
  17.     var messageCtrls = {};  
  18.    
  19.     var config = {  
  20.         // *example, this must be passed into init(config)  
  21.         fooSelector: null// $("#foo")  
  22.         messageSelector: null// $(".message")  
  23.         additionalMessageSelector: null// $(".additional_message")  
  24.         options: {  
  25.             showOK: true,  
  26.             showCancel: true,  
  27.             warningLevel: 1,  
  28.         }  
  29.     }  
  30.    
  31.     // AJAX calls  
  32.     var getMessage = function(message) {  
  33.         $.ajax({  
  34.             url: '/getMessagePage',  
  35.             type: 'POST',  
  36.             dataType: "json",  
  37.             data: {'message' : message},  
  38.             success: function(data) {  
  39.                 // ...  
  40.                 messageCtrls.mainMessageDiv.html(data.message);  
  41.                 // call bind controls to bind to the newly introduced dom elements  
  42.                 messageCtrls = bindMessageControls();  
  43.                 },  
  44.             error: function() {  
  45.                 // ...  
  46.                 }  
  47.         });  
  48.     };  
  49.    
  50.     var inputClick = function(event) {  
  51.         event.preventDefault();  
  52.         // depending on if you'll reuse these selectors throughout   
  53.         // the app I might have these as variables  
  54.         $('.loading').html('<img class="remove_loading" src="/graphics/loading.gif" alt="" />');  
  55.    
  56.         // try to avoid these  
  57.         var msg = $(".additionalMessage").val();  
  58.         // and use this   
  59.         var msg = config.additonalMessageSelector.val();  
  60.         // or  
  61.         var msg = pvtAdditionalMessageVal;  
  62.    
  63.         if (msg == ""){  
  64.             $("#message_empty").jmNotify();  
  65.             $('.remove_loading').remove();  
  66.         } else {  
  67.             getMessage(msg);  
  68.         }  
  69.     };  
  70.    
  71.     var bindMessageControls = function () {  
  72.         var self = {};  
  73.    
  74.         // Modal  
  75.         self.thisModal = $(".MessageModal");  
  76.    
  77.         // CheckBoxs  
  78.         self.fooCb = $(".foo_checkbox");  
  79.           
  80.         // Buttons  
  81.         self.okBtn = $(".btnOk");  
  82.         self.cancelBtn = $(".btnCancel");  
  83.    
  84.         // Divs  
  85.         self.mainMessageDiv = $(".main_message");  
  86.         self.additionalMessageDiv = $(".addtional_message");  
  87.    
  88.         //Help Icons  
  89.         self.HelpIcon = $(".help-icon");  
  90.    
  91.         return self;  
  92.     };  
  93.    
  94.     var bindVals = function () {  
  95.         //check to make sure we have a valid config passed in before we set the values  
  96.         if (!config.messageSelector) throw "Invalid configuration object passed in init()";  
  97.           
  98.         //bind the values to "private variables"  
  99.         pvtMessageVal = config.messageSelector.val();  
  100.           
  101.         //this control is optional, test existence  
  102.         if(config.additionalMessageSelector.length)  
  103.             pvtAdditionalMessageVal = config.additionalMessageSelector.val();  
  104.     };  
  105.    
  106.     var bindFunctions = function() {  
  107.         // you can use jQuery  
  108.         $("btnOk").on("click", inputClick)  
  109.         // but we have the controls object to use, so instead  
  110.         messageCtrls.okBtn.on('click, inputClick')  
  111.     };  
  112.    
  113.     var init = function () {  
  114.         messageCtrls = bindMessageControls();  
  115.         bindFunctions();  
  116.     };  
  117.    
  118.     var showMessage = function (cfg) {  
  119.         config = cfg;  
  120.         bindVals();  
  121.         messageCtrls.thisModal.modal({  
  122.             show: true,  
  123.             keyboard: false,  
  124.             backdrop: "static"  
  125.         });  
  126.     };  
  127.       
  128.     return {  
  129.         init: init,  
  130.         show: showMessage,  
  131.         getMessage: getMessage  
  132.         //anything else you want available  
  133.         //through myMessageApp.function()  
  134.         //or expose variables here too  
  135.     };  
  136.    
  137. })();  
  138.    
  139. //usage  
  140. $("document").ready(function () {  
  141.     myMessageApp.init();  
  142. });  
Points of Interest

This is the first in a series that will explore the Module Pattern in JavaScript. In the next part, I will break down the code in this example and explain in detail the whats and whys. Then I hope to show examples of other implementation of this pattern using objects, prototypes, and other variations such as the Revealing Module Pattern.

History

I'm a backend developer by trade moving into the in browser arena, so my post tends to be an effort to find a way to force structure on web development. If anyone else struggles in this area, please feel free to contact me.
 
Read more articles on JavaScript

 

Up Next
    Ebook Download
    View all
    Learn
    View all