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:[email protected]" 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: {  
  38.                 'message': message  
  39.             },  
  40.             success: function (data) {  
  41.                 // ...    
  42.                 messageCtrls.mainMessageDiv.html(data.message);  
  43.                 // call bind controls to bind to the newly introduced dom elements    
  44.                 messageCtrls = bindMessageControls();  
  45.             },  
  46.             error: function () {  
  47.                 // ...    
  48.             }  
  49.         });  
  50.     };  
  51.   
  52.     var inputClick = function (event) {  
  53.         event.preventDefault();  
  54.         // depending on if you'll reuse these selectors throughout     
  55.         // the app I might have these as variables    
  56.         $('.loading').html('<img class="remove_loading" src="/graphics/loading.gif" alt="" />');  
  57.   
  58.         // try to avoid these    
  59.         var msg = $(".additionalMessage").val();  
  60.         // and use this     
  61.         var msg = config.additonalMessageSelector.val();  
  62.         // or    
  63.         var msg = pvtAdditionalMessageVal;  
  64.   
  65.         if (msg == "") {  
  66.             $("#message_empty").jmNotify();  
  67.             $('.remove_loading').remove();  
  68.         } else {  
  69.             getMessage(msg);  
  70.         }  
  71.     };  
  72.   
  73.     var bindMessageControls = function () {  
  74.         var self = {};  
  75.   
  76.         // Modal    
  77.         self.thisModal = $(".MessageModal");  
  78.   
  79.         // CheckBoxs    
  80.         self.fooCb = $(".foo_checkbox");  
  81.   
  82.         // Buttons    
  83.         self.okBtn = $(".btnOk");  
  84.         self.cancelBtn = $(".btnCancel");  
  85.   
  86.         // Divs    
  87.         self.mainMessageDiv = $(".main_message");  
  88.         self.additionalMessageDiv = $(".addtional_message");  
  89.   
  90.         //Help Icons    
  91.         self.HelpIcon = $(".help-icon");  
  92.   
  93.         return self;  
  94.     };  
  95.   
  96.     var bindVals = function () {  
  97.         //check to make sure we have a valid config passed in before we set the values    
  98.         if (!config.messageSelector) throw "Invalid configuration object passed in init()";  
  99.   
  100.         //bind the values to "private variables"    
  101.         pvtMessageVal = config.messageSelector.val();  
  102.   
  103.         //this control is optional, test existence    
  104.         if (config.additionalMessageSelector.length)  
  105.             pvtAdditionalMessageVal = config.additionalMessageSelector.val();  
  106.     };  
  107.   
  108.     var bindFunctions = function () {  
  109.         // you can use jQuery    
  110.         $("btnOk").on("click", inputClick)  
  111.         // but we have the controls object to use, so instead    
  112.         messageCtrls.okBtn.on('click, inputClick')  
  113.     };  
  114.   
  115.     var init = function () {  
  116.         messageCtrls = bindMessageControls();  
  117.         bindFunctions();  
  118.     };  
  119.   
  120.     var showMessage = function (cfg) {  
  121.         config = cfg;  
  122.         bindVals();  
  123.         messageCtrls.thisModal.modal({  
  124.             show: true,  
  125.             keyboard: false,  
  126.             backdrop: "static"  
  127.         });  
  128.     };  
  129.   
  130.     return {  
  131.         init: init,  
  132.         show: showMessage,  
  133.         getMessage: getMessage  
  134.         //anything else you want available    
  135.         //through myMessageApp.function()    
  136.         //or expose variables here too    
  137.     };  
  138.   
  139. })();  
  140.   
  141. //usage    
  142. $("document").ready(function () {  
  143.     myMessageApp.init();  
  144. }); 
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