Design Patterns in JavaScript - Part 2

2 min readWeb DevelopmentSystems & Architecture

Revealing Module Patternvar userModule = (function () { ... })();private, in the closurevar db (WebSQL handle)createTable(tx)errorHandler(e)log(msg)returned → publicinit(callback)storeUser(user, callback)getUser(id, callback)"anything returned will become public"userModule.init(cb) → openDatabase, then create the tableuserModule.storeUser({ userName }, cb) → insertuserModule.getUser(1, cb) → selectdb and the helpers are not reachable from outsideAMD, with requirejsjquerybootstrapjq-datepickerrequirejs([deps], function ($) { ... })the three are loaded asynchronously, in parallel;the function runs only once all of them are in$('.datepicker').datepicker({ format: 'dd/mm/yyyy', ... })on <div class='datepicker'>no globals: each module receives its dependencies as argumentsdefine([deps], function (dep) { return { ... } }) exports a module
Two patterns from the post. Revealing module: a function expression runs once, keeps db and its helpers in its closure and returns an object holding only init, storeUser and getUser, so those are the module's public surface. AMD: requirejs loads jquery, bootstrap and the datepicker plugin asynchronously and calls the function only once all of them are present, with no global variables.

Hello folks! A month back I wrote a post explaining how basic fundamental design patterns could be written in JavaScript language. I received few emails of appreciation as well as advice and on one such advice, I am sharing my experience of the current patterns which actually align with your day to day development in JavaScript (this time it is specific to JavaScript). Lets get started -

1. Revealing Module Pattern

Anyone who started learning programming would have encountered the term Object Oriented Programming and in it Encapsulation. JavaScript, in particular does not enjoy the liberty of visibility modifiers like other languages do, but we do want to implement Encapsulation. Now, this can be achieved through this Revealing Module Pattern. Here is how the core syntax is like -

var myReveal = (function() {
    Properties
    Functions
    return { Anything you want to be public, return in form of Object  }
})();

Usage -

myReveal.ReturnedObjectProperty

I will not suggest to not know about closures, but if you are not willing to use closures to hide methods or properties, this method is really very handy. Lets write a simple real world example using WebSQL to get more clear understanding about this -

var userModule = (function() {
    var db; // Private Global Variable

    function createTable(transaction) {
        transaction.executeSql('create table if not exists diary(id INTEGER PRIMARY KEY AUTOINCREMENT, userName TEXT, published DATE)')
    };

    function errorHandler(e) {
        log(e);
    };

    function init(callback) {
        try {
            db = window.openDatabase("user", 1.0, "user", 2 * 1024 * 1024);
            db.transaction(createTable, errorHandler, callback);
        } catch (e) {
            errorhandler(e);
        }
    };

    function storeUser(userDetails, callback) {
        db.transaction(function(t) {
            t.executeSql('insert into user(userName,published) values(?,?)', [userDetails.userName, new Date().getTime()],
                function() {
                    callback();
                }, errorHandler);
        }, errorHandler);
    };

    function getUser(id, callback) {
        db.transaction(function(t) {
            t.executeSql('select from user where id = ?', [id],
                function(t, results) {
                    callback(results);
                }, errorHandler);
        }, errorHandler);
    };

    function log(msg) {
        console.log(msg);
    };

    // Anything returned will become public.
    return {
        init: init,
        getUser: getUser,
        storeUser: storeUser
    }
})();

// Usage

userModule.init(someFunction);
userModule.storeUser({
    userName: 'Prashant'
}, someFunction);
userModule.getUser(1, someFunction)

RevealingModule.js on GitHub Gist

2. Asynchronous Module Definition (AMD)

This pattern is slowly getting hold of all the internet now, because as the title says Asynchronous. It actually is an Asynchronous pattern that takes the best out of all the world and yet loads stuff in parallel. This pattern ensures not only encapsulation, but also avoids Global Variables, Namespaces and it works very well within the browser. Lets quickly get into the basic syntax -

// Import all modules in a single location
define(["libs/otherModuleName"],
    function(otherModuleName) {
        // Export your module as an object
        return {
            myFunction: function() {
                otherModule.otherExportedFunction() + 1;
            }
        };
    }
);

This is not it, its just a beginning. Anyways, lets talk about the actual usage part of this. I shall be using requireJs, it is a popular script loader that supports AMD. Cool!, lets build something with this. We shall create a simple script that will load Jquery DatePicker in DOM.

requirejs(['jquery', 'bootstrap', 'jq-datepicker'],
    function($) {
        $('.datepicker').datepicker({
            format: 'dd/mm/yyyy',
            language: 'da',
            keyboardNavigation: false,
            autoclose: true
        });
    });

// HTML Code

<div class='datepicker'></div>

Simple, isn’t it. Lets talk about advantages of this style -

  1. I am always sure that the dependencies are loaded before the defined function.
  2. I can simply extend this function to do all stuff required.
  3. None of the variables are global, hence no issue of messing up your design in browser.

AMD is definitely my favorite and long back I wrote a simple script that converts a flat json into a bootstrap table. Here is the link

That’s it folks for now!

As always, please Email to provide your comments.