Full Stack Solutions
Javascript Design Pattern (1)

Pattern in Large Scale JavaScript Applications (Part -2 of 8)

It is clear from the Part – 1 of the Post that what a Pattern is in the Software Development Process and why we use the Software Design Pattern and the factors for using design pattern in JavaScript.If you haven’t read the previous post, i will recommend you to please read it once to get the overview.

I am very big fan of JavaScript’s Module Design Pattern.That’s the Object Literal Pattern in the category of Modular Design pattern.

What is Module Pattern ?

The Module Pattern is one of the Design Pattern not only in Javascript only that encapsulates PRIVACY & STATE using Closures in
JavaScript.


scalable-javascript-design-patterns-27-728
It gives us the way to encapsulate the private and public methods and variables and protect our methods from the Global Scope.

Code Snippet :

Below is the example of Shopping Cart that’s being implemented with the Module Pattern.shoppingCart Module is itself a Global module.
Cart is an Array that’s Private so that other parts of the module can’t access it directly.

So only the methods (addProduct,getProductCount,getTotalProducts) that are within the module’s closure will be able to access it.

var shoppingCartModule = (function() {

    var cart = []; //private array
   
    return { 

        //exposed to public methods and variables

        addProduct: function(item) {
            cart.push(item);
        },

        getProductCount: function() {
            return cart.length;
        },

        getTotalProducts: function(){
           var total = this.getItemCount();
           p=0;
            while(total--){
                p+= cart[total].price; 
            }
            return p;
        }

    }

}());

Inside the shoppingCartModule we have return an object that gets automatically assigned to shoppingCartModule.
So you can access these methods by follows :

shoppingCartModule.addProduct({item:'JS Guide',price:$50});
shoppingCartModule.addProduct({item:'Design Pattern',price:$33});


console.log(shoppingCartModule.getProductCount());
console.log(shoppingCartModule.getTotalProducts());

So if you will try to access the shopingCartModule.basket this will not work because it will only work within the scope of the Closure.

 

Object Literal Pattern

The Object Literal Pattern is used to organise the code by the behaviours in your current Application’s Feature.So here we are preventing our application from the Global Variables which is a practice for Software Development Process and specially for the large scale JavaScript Applications.


scalable-javascript-design-patterns-36-728
 

It Modular JavaScript you can use the one module more than one time in your application like my project i want to get the Customer’s query in each page.So the functionality is going to be same for each page that taking the data of Query form on Submit Button click and then mail to my Email ID.

An object literal is a way to encapsulate related features, as shown here:

var myObjectLiteral = {
    myFearure1 : function() {
        /* do something */
    },

    myFeature2 : function() {
        /* do something else */
    }
};

  > Module Creation

Following Code snippet that is declaring a function that’s calling itself immediately.If you want to read more about it here.

    (function () {
          // code
    })();

JavaScript doesn’t have privacy, So we need to return only the parts we need and leaving the other code out of the global scope.

We have declared a myObjectLiteral Module in the global scope so that we can call it whenever want and wherever we want and we can also pass one module to the another modules.

  > Private Feature Methods :

Repeating the same call “JavaScript doesn’t have privacy” ,so it don’t have private methods too but we can create a working equivalent.


scalable-javascript-design-patterns-37-728
 

You all know what a Private method is,a method that can’t be call/see outside of the scope.So we can use the closure at
protecting our code.

 var myObjectLiteral = (function () {
  
          var privateMethod = function () {
            // your feautre code
          };

})();

In the above example myObjectLiteral is locally decalred inside the scope.So if we call that function outside of it’s scope
JavaScript will throw an error.

  > return in Modules :

Mostly Complex Modules use the return by returning an object to the Module.All methods are bound to that Object that can be accessible.

var myObjectLiteral = (function () {
  
    var localObject = {};

    var privateMethod = function () {};

    localObject.privateMethod = function() {

        // private method define

    };

    return localObject;


})();

  > Local Objects :

Local Objects are those which are declared inside the scope.In the last localObject is returned so we only get the actual/original Object sent back.

var myObjectLiteral = (function () {
  
    var localObject = {};

    var privateMethod = function () {};

    localObject.privateMethod = function() {

        // private method define

    };

    return localObject;


})();

Till now you have clear understanding of Modular Design Pattern.In the next Post We will understand Consolidate Jquery AJAX Calls and consuming this with our Modular Design Pattern.

 

Follow us

Don't be shy, get in touch. We love meeting interesting people and making new friends.

Most popular