Wednesday, February 9, 2011

Javascript Module Pattern and Augmentation

I have been learning about the Module Pattern for JavaScript and have a few notes to share.  Ben Cherry's post on the subject was extremely helpful and my intent here is merely to clarify a few points he made and add the concept of function augmentation.

Consider this code, which demonstrates Global Import, Module Export, and Loose Augmentation per Ben Cherry's post:

  1. /*global jQuery*/
  2. var EXAMPLE = (function (my, $) {
  3.     var _private_string = 'this string is private';
  4.     var _privateFunc;
  5.  
  6.     _privateFunc = function () {
  7.         alert('heads up: ' + _private_string);
  8.     };
  9.  
  10.     my.public_string = 'this string is public';
  11.  
  12.     my.publicFunction = function (input) {
  13.         alert('heads up: ' + my.public_string + input);
  14.     };
  15.  
  16.     return my;
  17. } (EXAMPLE || {}, jQuery));
  18.  
  19. var EXAMPLE = (function (my_root, $) {
  20.     my_root.MyClass = {};
  21.     my_root.MyClass.MySubClassOne = (function () {
  22.         var my = {};
  23.         var _sub_class_one_private = 'very private';
  24.         my.subClassOnePublicFunction = function () {
  25.             return 'public subclass 1';
  26.         };
  27.         return my;
  28.     } ());
  29.     my_root.MyClass.MySubClassTwo = (function () {
  30.         var my = {};
  31.         var _sub_class_two_private = 'also very private';
  32.         my.subClassTwoAugmentation = EXAMPLE.publicFunction;
  33.         EXAMPLE.publicFunction = function (input) {
  34.             my.subClassTwoAugmentation(input);
  35.             alert('EXAMPLE.publicFunction has been augmented');
  36.         };
  37.         return my;
  38.     } ());
  39.     return my_root;
  40. } (EXAMPLE || {}, jQuery));

The first block sets up the EXAMPLE module and the second block uses Loose Augmentation to add additional functions and classes, mimicking the namespacing conventions I am comfortable with from C# development.

Notice the subClassTwoAugmentation method.  This demonstrates how to augment the existing EXAMPLE.publicFunction function with additional code that will run after the original EXAMPLE.publicFunction code has completed.  I needed to learn this trick so that I could chain additional functionality onto an existing event handler in my production code.  I got the idea for this method from Douglas Crockford's JavaScript: The Good Parts in Chapter 4, Augmenting Types, and also from this forum post.

No comments:

Post a Comment