Showing posts with label Design Patterns. Show all posts
Showing posts with label Design Patterns. Show all posts

Monday, 21 December 2015

Implement the Chain Of Responsibility design pattern in Javascript

In this post we are going to see the Implementation of Chain of Responsibility design pattern in Javascript, Chaining means when a object is executed a function furthurly from the result set we can executed another set of functions

Ex: $(".txt")..load().click().focus();

sample code:




How we can manipulate the chaining of methods against the objects. Basic structure of the Chain of  Responsibility pattern




var chainPatter = function () {

};

chainPatter.prototype = {
    method1: function () {
        return this;
    },
    method2: function() {
        return this;
    }
}


From the above sample structure we are going to create a real one.



/* Chain of Responsiblity */
var HtmlEle = function (elementinp) {
    this.elementT = elementinp;
};

HtmlEle.prototype = {

    attachEvent: function (eventname, fun, capture) {
        _hook(this.elementT, eventname, fun, capture);
        return this;
    },
    click: function (fun) {
        this.attachEvent("click", fun, false);
        return this;
    },
    load: function (fun) {
        this.attachEvent("load", fun, true);
        return this;
    },
    blur: function (fun) {
        this.attachEvent("blur", fun, true);
        return this;
    },
    focus: function (fun) {
        this.attachEvent("focus", fun, true);
        return this;
    },
    windowLoad: function (fun) {
        this.attachEvent("DOMContentLoaded", fun, false);
        return this;
    },
    value: function () {
        return this.elementT.value;
    }
};



object of Htmlele is used to create a instance against the element then we can chaining the functions against the element.

How we can chaining the methods in the object, let we some code, then we see the real sample code.


new HtmlEle(document).windowLoad(fun).focus(fun);

 var fun = function (){
     console.log("called"); 
 }

Code:



/* using the chaining method in Module pattern*/
var HtmlParser = (function () {

    /* private construction */
    function findType(tagname) {
        var _searchType = tagname.substring(0, 1);
        if (_searchType == ".")
            return "class";
        else if (_searchType == "#")
            return "id";
        else
            return "tag";
    }

    return {
        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;
            }
            return new HtmlEle(_element);
        },
        _loadDocument: function (fun) {
            return new HtmlEle(document).windowLoad(fun);
        }
    }

})();



/* chain pattern to load the document and pass the callback */
HtmlParser._loadDocument(function () {

    var buttonEle = HtmlParser._element("#check");

    buttonEle.click(function () {
        alert(HtmlParser._element("#test1").value());
    })
        .focus(function () {
            console.log("focus");
        });

    HtmlParser._element("#bdy").load(function () {
        console.log("body loaded");
    });

    HtmlParser._element("#div1").blur(function () {
        console.log('out of focus');
    })
        .click(function () {
            console.log("div clicked");
        });

});





From this post you can learn how to create a Chain of Responsibility design pattern in JavaScript.

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 pattern
Import 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";
        else if (_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;
            }
            return new HtmlEle(_element);
        },
        _loadDocument: function (fun) {
            return new HtmlEle(document).windowLoad(fun);
        }
    }

})();


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


/* Module pattern variations */
/* Import Mixins */
var ModParser = (function (_parser) {

    var _obj = {};

    _obj.rootParser = _parser;
    _obj.GetElementValue = function (elementT) {
        return _parser._element(elementT).value;
    };

    return _obj;

})(HtmlParser);



/* Export globals */
var GlobalParser = (function (_parser) {

    var _obj = {};

    _obj.rootParser = _parser;
    _obj.SetElementValue = function (elementT, value) {
        _parser.rootParser._element(elementT).elementT.value = value;
        return elementT;
    };

    return _obj;

})(ModParser || {});


Calling a module pattern sample code:
*****************************************************


Advantages of Module pattern:
  1. Private data supports
  2. Provide the clean structure code
  3, Global declaration

Dis 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.