Pages

Monday, 21 December 2015

Implement the Module design Pattern in the Javascript

In this post we are going to see the Module pattern which is one of the design patterns present in the JavaScript, Module pattern is used to create the scopes with private and public access to the properties and methods in a structural way.Basic structure is global module, it is consists of a function defined in a global , private declarations are comes inside the functions with public things are declared in a return statement.

var Module = (function () {

/* Private declarations */

return {

/* public declarations */

};

})();

Some types present in the Module patternImport external libraries:

var Module = (function (_mod) {

return {};

})(AnotherMod);

Global Module:var Module = (function () {

return {};

})();

Let we see some example where we will create a HTMLParser which will works like Jquery library, We will see some sample in both the types.Global Module:

/* Module pattern*/

var HtmlParser = (function () {

/* private construction */

function findType(tagname) {

var _searchType = tagname.substring(0, 1);

if (_searchType == ".")

return"class";

elseif (_searchType == "#")

return"id";

else

return"tag";

}

return {

/* publicconstruction */

GetValue: function (elementT) {

var _type = findType(elementT);

var _element;

switch (_type) {

case"class":

_element = document.getElementsByClassName(elementT.substr(1));

break;

case"id":

_element = document.getElementById(elementT.substr(1));

break;

case"tag":

_element = document.getElementsByTagName(elementT);

break;

}

return _element.value;

},

_element: function (elementT) {

var _type = findType(elementT);

var _element;

switch (_type) {

case"class":

_element = document.getElementsByClassName(elementT.substr(1));

break;

case"id":

_element = document.getElementById(elementT.substr(1));

break;

case"tag":

_element = document.getElementsByTagName(elementT);

break;

}

returnnew HtmlEle(_element);

},

_loadDocument: function (fun) {

returnnew HtmlEle(document).windowLoad(fun);

}

}

})();

Import Module :In this sample we can see that we are importing the HtmlParser in to the new Module pattern

Advantages of Module pattern: 1. Private data supports 2. Provide the clean structure code 3, Global declarationDis Advantages of Module Pattern:1. not able to override the functionality of methods.From this post you can learn the Module pattern present in the JavaScript and how to implement that kind of patterns in the code.