Wednesday, 18 January 2017

Javascript Design Pattern



Hi, Today we will learn to write a very basic modular pattern of JavaScript. But before going ahead we should first familiar with what design pattern actually do.
Design pattern represents that code is written by experienced object oriented software developers.
So as we write daily multiple codes, and if we did not organised our code then day by day it goes complex. We can prevent from being a irritated developers by organizing our code.

We are going to learn a very basic of modular pattern that is commonly used by experience developers.

Suppose we have to do multiple calculation and for this we have to write too many functions and if we organized it in patterns it become readable. Here my calculation function will store all calculation functions and based on its default calling on calculation function load.

Syntax:-       var myFunction = function(){
                                    var fun1 = function(){}
                                     var fun2 = function(){}
                      return{ one: fun1,two:fun2}
                    };



var MyCalculation = function () {

//Here we can define our private variable that we can access in functions.

var addOperation = function (a, b) {
        alert(a + b);
    };
var subtrOperation = function (a, b) {
        alert(a - b);
    }


return {

 //Here you can define public accessibility for this Complete function.  
//Note in our whole function this is only entry and exist which will returned.

        add: addOperation ,
        subtract: subtrOperation ,
        multiple: function (a, b) {
            alert(a * b);
        }
    }
};

Now calling part 

//For using our modular function we first need to create an instance for our function.

var calculation = new MyCalculation ();
calculation .add(1, 2);
calculation .subtract(5, 1);
calculation .multiple(2, 4);

simple.....



Now i am going to explain another function which we can use to enhance our programming experience in javascript. Below given app i have studied from google and just want to clear how to program such apps.

As for beginner, it wouldn't be easy to understand so for faster to study i am writing points as numbers 1,2,3,4 you can go with these steps, so that it become easier to study.
In my case i will point function caller as point 1.





 
var myWebApp = (function() {
    "use strict"
 
 
 
 var myDiv= $("#myDiv"); // Getting Div Id  
 
    // private variables  
    var privateMessageVal;
    var privateAdditionalMessageVal;
   
   //Create an object which will hold our messages.

    var messageCtrls = {};
 
    var myconfigfile = {

        mySelector: null, // $("#myDiv")
        messageSelector: null, // $(".message")
        additionalMessageSelector: null, // $(".additional_message")
        options: {
            showOK: true,
            showCancel: true,
            warningLevel: 1,
        }
    }
 
writing ajax call functions for all events as a dynamic, in which we can pass parameter and result will be bind to messageCtrls object.


    // AJAX calls
    var getResult = function(msgs) {   ---------------------------------  (Point 8)
        $.ajax({
            url: '/urlOfAction',
            type: 'POST',
            dataType: "json",
            data: {'message' : msgs},
            success: function(data) {
                // ...
                messageCtrls.mainMessageDiv.html(data.result);
             
               //Here i am binding default controls for any dom to messageCtrls.

                messageCtrls = bindMessageControls();
                },
            error: function() {
                // ...
                }
        });
    };
 
    var inputClick = function(event) {   ---------------------------------  (Point 7)
        event.preventDefault();
        // depending on if you'll reuse these selectors throughout
        // the app I might have these as variables

        $('.loading').html('<img class="remove_loading" src="/graphics/loading.gif" alt="" />');
 
        // try to avoid these
        var msgs = $(".additionalMessage").val();
        // and use this
        var msgs = myconfigfile.additionalMessageSelector.val();
        // or
        var msgs = privateAdditionalMessageVal;
 
        if (msgs == ""){
            $("#msgs_empty").notification();   ////validating field if it is empty. and if not then call to ajax.
            $('.remove_loading').remove();
        } else {
            getResult(msgs);
        }
    };
 
//Here we will write all default controls needed for our App.

    var bindMsgControls = function () {
        var self = {};
 
        // Modal
        self.thisModal = $(".MessageModal");
 
        // CheckBoxs
        self.fooCb = $(".foo_checkbox");
       
        // Buttons
        self.okBtn = $(".btnOk");   ---------------------------------  (Point 6)
        self.cancelBtn = $(".btnCancel");
 
        // Divs
        self.mainMessageDiv = $(".main_message");   ---------------------------------  (Point 9)
        self.additionalMessageDiv = $(".addtional_message");
 
        //Help Icons
        self.HelpIcon = $(".help-icon");
 
        return self;
    };
 
    var bindVals = function () {
        //check to make sure we have a valid config passed in before we set the values
        if (!myconfigfile.messageSelector) throw "Invalid configuration object passed in init()";
       
        //bind the values to "private variables"
        pvtMessageVal = myconfigfile.messageSelector.val();
       
        //this control is optional, test existence
        if(config.additionalMessageSelector.length)
            pvtAdditionalMessageVal = myconfigfile.additionalMessageSelector.val();
    };
 
    var bindAllFunctions = function() {   ---------------------------------  (Point 4)
     
//This function will bind function to controls that are taken in bindMsgControls
//We can directly take our controls and bind function to them or we can call to object's controls, here messageCtrls's okBtn that is called by bindMsgControls, here we can get them and call function on its events.

        $("btnOk").on("click", inputClick)
     
//We can use as above but we have controls's object so we will write

        messageCtrls.okBtn.on('click, inputClick')   ---------------------------------  (Point 5)
    };
 
// On Init Call We need to bind controls and their functions first.

    var init = function () {   ---------------------------------  (Point 3)
        messageCtrls = bindMsgControls();
        bindAllFunctions();
    };
 
    var showMessage = function (cfg) {
        myconfigfile = cfg;
        bindVals();
        messageCtrls.thisModal.modal({
            show: true,
            keyboard: false,
            backdrop: "static"
        });
    };
   
    return {
        init: init,   ---------------------------------  (Point 2)
        show: showMessage,
        getMessage: getResult
        //anything else you want available
        //through myMessageApp.function()
        //or expose variables here too
    };
 
})();
 


//Usage

//A call to our above app init function

(Point 1)
--------------

$("document").ready(function () {
    myMessageApp.init();
});

So in totally we need to take care of 8 to 9 points which can clear our view. Here only our init of myapp will bind all controls and its functions, events, errors and pass it to its respective div.

That's way we can make our code look like self app. You can write in various ways but this technique will definitely perfect for modular pattern.




0 comments:

Post a Comment