Ways of Writing JavaScript using Design Patterns


We all know about design patterns in Object oriented Programming but do you know that we also have design patterns in JavaScript? The answer is Yes we do have. But hardly few people know about it. Lets have a spin around in different type of JavaScript.

Fundamentals : Design Pattern and JavaScript



1. Types of Design Pattern Widely used
2. MVC and MVVM Pattern

Fundamentals: Design Patterns



What is a Pattern?


A pattern is a reusable solution that can be applied to commonly occurring problems in software design. In our case Java scripts.

Why Pattern ?


More testable, extensible and maintainable code. Separation of Concerns.

When is software design a valid pattern ? Rule of three
Pattern is considered to be valid if it display some recurring phenomenon. Example: Jquery $("Selector")

Rule of Three


Fitness of purpose - how is the pattern considered successful?
Usefulness - why is the pattern considered successful?
Applicability - is the design worthy of being a pattern because it has wider applicability? If so, this needs to be explained.

When reviewing or defining a pattern, it is important to keep the above in mind.

Types of Design Patterns


Creational Design Pattern: object creation.
Structural Design Pattern: object compositions and relationships between them.
Behavioral Design Pattern: communication between disparate objects.


Everything in JavaScript are objects
JavaScript Functions can be considers as class in OOPS
IIFE- Immediately invoke function expression
'this' keyword and scope


Most Widely Used Types of Design Pattern



Constructor Pattern
Module Pattern
Revealing Module Pattern
Observer Pattern or Pub/Sub Pattern


Constructor Pattern



In OOPS Constructor is a special method used to initialize a newly created object

Object Creation –


The three common ways to create new objects in JavaScript are as follows:

var newObj = {};
var newObj = Obj.create( null );
var newObj = new Obj();

Creating Properties



1. Dot syntax

newObj.property = "New Property";
var key = newObj.property;

2. Square bracket syntax

newObj["property"] = "New Property";
var key = newObj["property"];


Constructor Pattern Example:


	
function Employee(Name, DOB, Marks) {
this.Name = Name;
this.DOB = DOB;
this.Marks = Marks;

this.toString = function () {
return this.Name + " has done " + this.Marks + " Marks";
};
}

// Usage:

// We can create new instances of the Employee
var Imran = new Employee("Imran", 2009, 100);
var Rahul = new Employee("Rahul", 2010, 50);


PROTOTYPE Constructor



function Employee(Name, DOB, Marks) {
this.Name = Name;
this.DOB = DOB;
this.Marks = Marks;

}

Employee.prototype.toString = function () {
return this.Name + " has done " + this.Marks + " Marks";
};

// Usage:

var Imran = new Employee("Imran", 2009, 100);
var Rahul = new Employee("Rahul", 2010, 50);


The Module Pattern



Modules
Privacy


Modules



Modules are an integral piece of any robust application's architecture and typically help in keeping the units of code for a project both cleanly separated and organized.


Module Pattern in Software Engineering



The Module pattern was originally defined as a way to provide both private and public encapsulation for classes in conventional software engineering.

Module Pattern in JavaScript



Used to emulate the concept of classes in such a way that we're able to include both public/private methods and variables inside a single object
Shielding particular parts from the global scope
Avoiding Likelihood of our function names conflicting with other functions


Module Pattern Example:



var namespace = namespace || {};
namespace.Lottery = (function (ns) {

var pokerAlgo = function () {

return Math.floor(Math.random() * 11);
}

return {

pokeroutput: function () {
alert('Your Lucky Number is ' +pokerAlgo());
}
}
})(namespace);

Privacy



Wrapping a mix of public and private methods and variables, protecting pieces from leaking into the global scope and accidentally colliding with another developer's interface

The Revealing Module Pattern




Makes reading code easier and allows it to be organized in a more structured manner.
The pattern starts with defining a variable, associate it with a function and then invoke the function immediately as the script loads.
Expose the methods via shorter names
Hide all the Functions in Private block rather than defining them in the return block which makes them public

The Revealing Module Pattern Example:



var Lottery = (function () {

var pokerAlgo = function () {

return Math.floor(Math.random() * 11);
}

function PokerResult() {
alert('Your Lucky Number is ' + pokerAlgo());
}


return {
pokeroutput: PokerResult

}
})();


Observer Pattern or Pub/Sub Pattern



Methods in Observer Pattern



publish(data or Subject)- Notify(): Called by the subject to Notify Observers
subscribe(observer): Called by the subject to add observer
unsubscribe(observer): Called by the subject to remove an observer

Observer Pattern or Pub/Sub Pattern Example:



$(window).load(function () {
$.fn.observe = function (eventName, callback) {
return this.each(function () {
var el = this;
$(document).on(eventName, function () {
callback.apply(el, arguments);
})
});
}



$('#div1').on('click', function (e) {
$(this).trigger('custom');//Notify
});

$('#div2').observe('custom', function (e) { //observer
$(this).css('color', 'green');
$(this).text('Observer - Div 2 Color:Green');
});

$('#div3').observe('custom', function (e) {//observer
$(this).css('color', 'green');
$(this).text('Observer - Div 3 Color:Green');
});

});


Comments

No responses found. Be the first to comment...


  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: