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