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

Post a Comment

Popular posts from this blog

File upload and Progress events with HTML5 XmlHttpRequest Level 2

The XmlHttpRequest Level 2 specification adds several enhancements to the XmlHttpRequest object. Last week I had blogged about cross-origin-requests and how it is different from Flash\Silverlight's approach .  With Level 2 specification one can upload the file to the server by passing the file object to the send method. In this post I'll try to explore uploading file using XmlHttpRequest 2 in conjunction with the progress events. I'll also provide a description on the new HTML5 tag -  progress which can be updated while the file is being uploaded to the server. And of course, some ColdFusion code that will show how the file is accepted and stored on the server directory.

Server sent events with HTML5 and ColdFusion

There are several ways to interact with the server apart from the traditional request\response and refresh all protocol. They are polling, long polling, Ajax and Websockets ( pusherapp ). Of all these Ajax and Websockets have been very popular. There is another way to interact with the server such that the server can send notifications to the client using Server Sent Events (SSE) . SSE is a part of HTML5 spec:  http://dev.w3.org/html5/eventsource/

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.