23 April, 2012

Revealing Module Pattern in JavaScript


Revealing Module Pattern makes the code to read better and more structured way, This really useful when we had to repeat the name of the main object when we wanted to call one public method from another or access public variables. This is done by adding a return statement at the end of the function that exposes the public members.

The benefits of this approach are. The Revealing Module Pattern allows the syntax of your script to be fairly consistent - it also makes it very clear at the end which of our functions and variables may be accessed publicly, something that is quite useful. In addition, we also able to reveal private functions with more specific names if we wish.

The following code demonstrates how the module can be revealed.
var myModule = (function () {
 
    var name = 'Mohamed Rafeeq';
    var age = 28;
 
    function updatePerson() {
        name = 'Mohamed Rafeeq Updated';
    }
    function setPerson() {
        name = 'Mohamed Rafeeq Set';
    }
    function getPerson() {
        return name;
    }
    return {
        set: setPerson,
        get: getPerson
    };
} ());
() –> Indicate the self invoking, this act as singleton call to myModule.
This can be called as below

myModule.get();

For more reference, read below posts:
http://weblogs.asp.net/dwahlin/archive/2011/08/02/techniques-strategies-and-patterns-for-structuring-javascript-code-revealing-module-pattern.aspx
http://weblogs.asp.net/dwahlin/archive/2011/08/03/techniques-strategies-and-patterns-for-structuring-javascript-code-revealing-prototype-pattern.aspx
http://blog.davidlitmark.com/post/6009004931/an-introduction-to-the-revealing-module-pattern