Skip to main content

Module Pattern in JavaScript

Couple of days back I wrote about the Constructor Pattern in JavaScript wherein I explained how classes can be simulated using functions in JavaScript. Also, on how the prototype property can be used to extend another class. The other important element in any of the Object-Oriented programming language is the concept of encapsulation i.e. providing private members that can be accessed only by the members of the same class. I came across the Module Pattern today and found that it is quite easy to achieve encapsulation in JavaScript. Though the variables in JavaScript can't be declared as private or public, but closures can be used to emulate encapsulation.

The var scoped variables defined inside a function are visible throughout the body of the function and will die once the function has completed its execution. This means that the var scoped variables can't be accessed outside the function and hence can be considered as 'private' variables of a class. This is exactly what we want from a JavaScript class, but there should be a way to access or update these members through a public interface. The member functions or variables can be made public by returning an object from that function. Here's is a simple module:

twitter = (function() { var twitterStatus = []; var currentIndex = 0; var getPreviousElement = function() { if(currentIndex != 0) return twitterStatus[--currentIndex]; else return twitterStatus[0]; } var getNextElement = function() { if(currentIndex != twitterStatus.length-1) return twitterStatus[++currentIndex]; else return twitterStatus[currentIndex]; } var pushMessage = function(message) { twitterStatus.push(message); } return { pushMessage: pushMessage, getPreviousElement: getPreviousElement, getNextElement: getNextElement } })();

There are quite a few things happening here. Firstly, I'm defining a self invoking function which is then assigned to a variable 'twitter'. When the function is invoked the various member variables and functions are defined and the function returns with an object containing references to these member functions. Now the variable 'twitter' can be used to invoke various functions (public methods). These functions are nothing but closures and will have read\write access to the private members (var scoped variables) of the function:

twitter.pushMessage("Message 1"); twitter.pushMessage("Message 2"); twitter.getPreviousElement(); twitter.getNextElement();

In this way it is more easier to organize the code in a particular namespace and not worry about other library functions present in the global namespace.

Comments

  1. I highly recommend looking into Asynchronous Module Definitions (AMD) as a fully-developed JavaScript module build method: http://requirejs.org/docs/whyamd.html

    ReplyDelete
  2. I have started to look at various design patterns in JavaScript. I'll definitely look into AMD. Thanks for sharing it.

    ReplyDelete
  3. That is actually the revealing module pattern.

    ReplyDelete
  4. If you're a fan of the Module Pattern, take a look at the Definitive Module Pattern as well:
    https://github.com/tfmontague/definitive-module-pattern

    ReplyDelete

Post a Comment

Popular posts from this blog

Custom validation messages for HTML5 Input elements using the constraint validation API

HTML5 has introduced several input types such as EMAIL, URL, RANGE, SEARCH, DATE, TIME, etc,. Most of the modern browsers have implemented them and are ready to be used in a HTML document. Another exciting feature introduced in HTML5 is the form validation. Instead of writing JavaScript to validate users input, browsers can now validate it and show an appropriate message if the validation fails. The validation message is shown in line with the field for which the validation has failed. The default error message is shown when the validation fails. In this post I'll explain how these error messages can be changed.

Adding beforeRender and afterRender functions to a Backbone View

I was working on a Backbone application that updated the DOM when a response was received from the server. In a Backbone View, the initialize method would perform some operations and then call the render method to update the view. This worked fine, however there was scenario where in I wanted to perform some tasks before and after rendering the view. This can be considered as firing an event before and after the function had completed its execution. I found a very simple way to do this with Underscore's wrap method.

A cheat sheet of keyboard shortcuts in ColdFusion Builder

In my last post I have explained about keyboard shortcuts in ColdFusion Builder 2.0. This blog post contains a list of all shortcut keys and I have listed these keyboard shortcuts based on the categories that it falls into. Well, this post was not planned since users can easily get to know the keyboard shortcuts by navigating to the preferences (ColdFusion -> Profiles -> Keys). However, I met Joshua at Scotch on the rocks in Edinburgh and he suggested that it would be nice to have the list of keyboard shortcuts handy. So this post is for those who would like to have the list with them and refer it whenever required.


Keyboard shortcuts for inserting text:

These are the keyboard shortcuts which are used to insert some text into the editor:

CommandKeyboard shortcuts on WindowsKeyboard shortcuts on MacInsert anchor tagCTRL + T, LCMD + T, LInsert bold tagCTRL + T, BCMD + T, BInsert br tagCTRL + T, RCMD + T, RInsert cfabortCTRL + T, ACMD + T, AInsert cfdumpCTRL + T, DCMD + T, DInsert cfs…