Patterns in Large Scale JavaScript Applications, Part 2
In today's post, we take a look at the modular design pattern common to large-scale JavaScript web applications, and some common ways it's used.
Join the DZone community and get the full member experience.
Join For FreeIt is clear from Part 1 of this series what a pattern is in the software development process, why we use software design patterns, and the factors for using design patterns in JavaScript. If you haven’t read the previous post, i would recommend you to please read it once to get the overview.
I am a very big fan of JavaScript’s module design pattern. That’s the object literal pattern in the category of modular design patterns.
What Is a Module Pattern?
The module pattern is one of the design patterns, not only in Javascript, that encapsulates PRIVACY and STATE using Closures.
It gives us a way to encapsulate the private and public methods and variables and to protect our methods from the global scope.
Code Snippet:
Below is the example of a Shopping Cart that’s being implemented with the module pattern. The Shopping Cart 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;
}
}
}());
InsideshoppingCartModule
, we have returned an object that gets automatically assigned to shoppingCartModule
.
So you can access these methods as 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 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 organize code by the behaviors in your current application’s features. So, here, we are preventing our application from accessing the global variables, which is common a practice for software development, and especially, for large-scale JavaScript applications.
In modular JavaScript, you can use one module more than one time in your application, like the project in which I want to get the customer’s query to register on each page. So the functionality is going to be same for each page that's taking the data from the query form when the Submit button is clicked, and then an email will be sent 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
The following code snippet is declaring a function that’s calling itself immediately. If you want, you can read more about it here.
(function () {
// code
})();
JavaScript doesn’t have privacy, so we need to return only the parts we need and leave 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 and wherever we want, and we can also pass one module to the other modules.
Private Feature Methods:
Again, since “JavaScript doesn’t have privacy,” it doesn’t have private methods either. But we can create a working equivalent.
You all know what a private method is, it's a method that can’t be called/seen outside of its scope. So we can use the closure to protect our code.
var myObjectLiteral = (function () {
var privateMethod = function () {
// your feautre code
};
})();
In the above example, myObjectLiteral
is locally declared inside the scope. So if we call that function outside of its scope, JavaScript will throw an error.
Return in Modules:
Mostly complex modules use the return
function 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 below code, 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;
})();
I hope now you have a clear understanding of the modular design pattern. In the next post, we will look at how to consolidate jQuery Ajax calls and consume them with our modular design pattern.
Published at DZone with permission of Puneet Sharma, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments