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:
- /*global jQuery*/
- var EXAMPLE = (function (my, $) {
- var _private_string = 'this string is private';
- var _privateFunc;
- _privateFunc = function () {
- alert('heads up: ' + _private_string);
- };
- my.public_string = 'this string is public';
- my.publicFunction = function (input) {
- alert('heads up: ' + my.public_string + input);
- };
- return my;
- } (EXAMPLE || {}, jQuery));
- var EXAMPLE = (function (my_root, $) {
- my_root.MyClass = {};
- my_root.MyClass.MySubClassOne = (function () {
- var my = {};
- var _sub_class_one_private = 'very private';
- my.subClassOnePublicFunction = function () {
- return 'public subclass 1';
- };
- return my;
- } ());
- my_root.MyClass.MySubClassTwo = (function () {
- var my = {};
- var _sub_class_two_private = 'also very private';
- my.subClassTwoAugmentation = EXAMPLE.publicFunction;
- EXAMPLE.publicFunction = function (input) {
- my.subClassTwoAugmentation(input);
- alert('EXAMPLE.publicFunction has been augmented');
- };
- return my;
- } ());
- return my_root;
- } (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