Friday, April 15, 2011

JavaScript, the revealing module pattern

Lately I have been doing a lot of things with JavaScript and jQuery.  After doing some research I found some information on the revealing module pattern.  This pattern has really helped me to organize the work I do in JavaScript.  I find this to be very easy to read and debug.

  1. var Module1 = function () {
  2.     var selectors = {
  3.         nameTextBox: '#nameTextBox',
  4.         cancelButton: '#cancelButton'
  5.     }
  6.  
  7.     var urls = {
  8.         cancelUrl: 'http://homepage.com'
  9.     }
  10.  
  11.     var privateFunction1 = function (msg) {
  12.         alert(msg);
  13.     }
  14.  
  15.     var privateFunction2 = function (msg) {
  16.         privateFunction1(msg);
  17.     }
  18.  
  19.     var init = function () {
  20.         $(selectors.cancelButton).click(function () {
  21.             window.location = urls.cancelUrl;
  22.         });
  23.     }
  24.  
  25.     return {
  26.         selectors: selectors,
  27.         urls: urls,
  28.         init: init,
  29.         publicFunction: privateFunction2
  30.     }
  31. } ();
  32.  
  33. $(document).ready(function () {
  34.     Module1.init();
  35.  
  36.     Module1.publicFunction("Testing 123");
  37. });

The module consists of lines 1 – 31, you can see that all items defined in the module are locally scoped to the module.  Lines 25 – 30 define what will be publicly accessible outside of the module.  Note that line 29 defines a different public name in comparison to its internal name.  Also note that objects inside of the module can access each other.  Line 16 is calling the private function on line 11.  Trying to call privateFunction1 from outside the module would not be possible.

Also in this example I am showing some common things I like to do.  For example lines 2 – 5 define an object for selectors.  I make this selector object public incase the page that consumes this module needs to change the values.  Everywhere else in the module I call the selectors from the selector object.  This way if I need to change a value either manually in this script or dynamically from the page it is only done in one place.  Note lines 7 – 9 define the same thing although this time its urls.  Since I do a lot of my work in MVC I assign the url values on the consuming page using the url helpers.

In another post I will go over the organization and utilization of this pattern in an MVC 3 application.