Use of KnockoutJS Template Feature

In this article I will try to cover the usage of KnockOut JS template feature. If you want to learn basics of knockoutJS then the tutorial (http://learn.knockoutjs.com/#/?tutorial=intro) from knockout website is best place to start with.

 So here we are creating a simple website with help of knockoutJS template feature and other libraries e.g. jQuery, bootstraps etc. The website is simple, it has left navigation and once you click on the link respective article will get opened.

The final look of the website is depicted below.

website final look

Prerequisite: To understand this application, you should have basic understanding of following topics.

  • Basic understanding of HTML, JavaScript, CSS and JQuery.
  • Very basics of KnockoutJS libraries, you can quickly learn about knockoutJS from their training website as I have mentioned at the starting of the article.
  • I am using bootstrap for layout of the website.
  • I am using css for the look and feel of the website.

 

So before starting this example let’s discuss template feature briefly of knockoutjs.

Template Binding is a wonderful feature for populating DOM element with the results of rendering template.

Template feature provides you convenient way for building sophisticated UI structures -possibly with repeating or nested blocks - as a function of your view model data.

To know more about template-binding using knockoutJS refer their own article/tutorial (http://knockoutjs.com/documentation/template-binding.html ) .

Coming to the folder structure of the application, I am following the Progressive Enhancement pattern.

Below is the list of folders and their contents

css : contains css files (files used for managing look and feel of the website)

js: contains JavaScript code being used in the applications, you can further organize it based on the module, if your application is big.

data: This folder contains application data being used by the website, I have created a file (JSON) which contains website’s information, generally these kind of information needs to  be stored in database etc. 

images: Image folder used for images being used for website.

lib: lib folder contains js libraries being used by the website.

views: View folder contains all html files being used by the website and it is further structured by sub-folder as per the contents of the website.

So let's go through the files which are base for the website.

home.html

This is the main file where the complete layout of the website is defined. The website’s layout has (Header, Left Navigation, Content section, Right side navigation (If you want to add anything) and footer).  Nothing much to talk about this file, the code itself is self explanatory (class name "col-md-*" is part of bootstrap css).

<!DOCTYPE html>
<html lang="en">
	<head>
	
		<link rel="stylesheet" type="text/css" href="css/jquery-ui.min.css" />
		<link rel="stylesheet" type="text/css" href="css/jquery-ui.structure.min.css"/>
		<link rel="stylesheet" type="text/css" href="css/jquery-ui.theme.min.css"/>
		<link rel="stylesheet" type="text/css" href="css/demo.css" />
		<link rel="stylesheet" type="text/css" href="css/bootstrap.min.css" />
		<link rel="stylesheet" type="text/css" href="css/bootstrap-theme.min.css" />
	</head>
	
	<body>
	<div id="main-body">
		<div id="body-content" class="container">
			<div class="row">
				<!-- Header Navigation section -->
			   <div class="col-md-12" id="header-nav"> 
			   </div>
			</div>
			
			<div class="row">
				<!-- Left Navigation section (It's upto you how you want to represent your left navigation)-->
			   <div class="col-md-2" id="left-nav">
			   </div>
				<!-- Center section used for displaying content you have selcted 
				from the left navigation section -->		
			   <div class="col-md-8">
				<div class="mycontainer">
					<div id="container-example">
					</div>
					  
				</div>
			  </div>
			  <!-- This section you can use for anything, I have mentioned to show Advertisement on your website  -->
			   <div class="col-md-2">
				<div id="advt-container">
							
				</div>
			  </div>
			</div>
			 <!-- Footer section  -->
			<div class="footer">&copy; Deepak Singh</div>
		</div>
	  </div>
	</body>
	
	<script type='text/javascript' src='lib/knockout3.1.js'></script>
	<script type='text/javascript' src='lib/jquery1.js'></script>
	<script type='text/javascript' src='lib/jquery-ui.min.js'></script>
	<script type="text/javascript" src='lib/bootstrap.min.js'></script>
	<script type="text/javascript" src='js/navhandling.js'></script> 
	
</html>

 

So let's see how we can use template binding feature of knockoutJS for rendering header information. Header information binding has been done with help of two files header.html and headermodel.js.

 headermodel.js

headerMessageViewModel = function(){
	this.headerMessage={
			headertitle: 'Knockout Template Example!!!!', 
			menus:[{title:"About Me", page:"about.html"}]
	};
	
}
ko.applyBindings(new headerMessageViewModel(), document.getElementById("container-header"));

 

In the above code, if you see I have created headerMessageViewModel  JavaScript variable which I am binding with DOM element id named "container-header". We would able to understand and connect this code very well when we will see header.html code. And also a complete integration (displaying all header information in header navigation section of main page) of header information with main template file (home.html).

header.html

<!DOCTYPE html>
<html lang="en">
	<head>
		<!-- Creating headermenutemplate for displaying header menu -->
		<script type="text/html" id="headermenutemplate">
				
			<a href="#" data-bind="click:function(){$('#container-example').load('views/'+$data.page); }">
				<span data-bind="text:menu.title"> </span>
			</a>
				
		</script>
		<!-- Creating headertemplate for displaying header title and header menu 
			for displaying menus being used by the website
		-->
		<script type="text/html" id="headertemplate">
			<h3 data-bind="text:headertitle"> </h3>	
			<span id="header_menu" data-bind="template:{name:'headermenutemplate', foreach:menus, as:'menu'}">
			</span>
		</script>
		
        <script type='text/javascript' src='headermodel.js'></script>
	
    </head>
    <!-- This section of DOM is binded in headermodel.js. "headertemplate" is the name defined above in the script tag.-->
    <div id="container-header" class="header">
         <div class="header" data-bind="template:{name:'headertemplate', data:headerMessage}">
         </div>       
    </div>
    
</html>

 

So let's understand the each section of the above "header.html" code.

Below is the div section we are binding (ko.applyBindings(new headerMessageViewModel(), document.getElementById("container-header"));) in the headermodel.js file.
<div id="container-header" class="header"> <div class="header" data-bind="template:{name:'headertemplate', data:headerMessage}"> </div> </div>

Understand the template binding for displaying header title and menu in steps.

1. In heademodel.js ko.applyBindings() method is basically used for binding the 'headerMessageViewModel' JavaScript object to the specific dom element "container-header".
headerMessageViewModel function contains "headerMessage" object which in turns contains two properties "headertitle" and "menus" array.

2. Now in "header.html" of code section we are using "data-bind" (data-bind is the way to link data to the UI, please refer article http://knockoutjs.com/documentation/binding-syntax.html for more understanding) to whom we are telling template name and JavaScript object which we have bound in headermodel.js file (i.e. headerMessage).
So you can think of that, we are telling the headertemplate that use headerMessage data for extracting or rendering information.

<div class="header" data-bind="template:{name:'headertemplate', data:headerMessage}"> </div>

3. So in second step, now we know the template name and the data needed for the template (headertemplate). And from the below code you can understand how we are using headerMessage for displaying header title and passing menus data to another template.

<script type="text/html" id="headertemplate"> <!-- template name given above -->
<!-- here we are displaying header title, which is property of headerMessage object -->
<h3 data-bind="text:headertitle"> </h3>
<!-- here we are menus array, part of headerMessage object using data-bind to "headermenutemplate" -->
<span id="header_menu" data-bind="template:{name:'headermenutemplate', foreach:menus, as:'menu'}">
</span>
</script>

4. Here we are displaying menus defined.

<script type="text/html" id="headermenutemplate">
<!-- Here I am binding click event and opening the content in div section ("container-example") of home.html -->
<a href="#" data-bind="click:function(){$('#container-example').load('views/'+$data.page); }">
<span data-bind="text:menu.title"> </span>
</a>

</script>

So this is how header information has been displayed using knockoutjs template binding feature.

Understand the template binding for displaying left navigation as an accordion view

You have already seen the home.html code where it has section for left navigation. So now we will understand how we have to populate left navigation menu using knockout JS template binding.

left-nav.html

<!DOCTYPE html>
<html lang="en">
	<head>
		
        <script type="text/html" id="topicListTemplate">
			<!-- Binding click event on Menu title name -->	   
			<p class="menu-content-title" data-bind="click: function (){navlink($data.id, $data.page);} , attr: {'id': $data.id}">
				<strong>
					
					<span class="menu-text-middle" data-bind="text:topic.topicname"> </span> 
				</strong>
				
				<small> <span data-bind="html:topic.breifdesc"> </span></small>
			</p>
			
			<div class="menu-seprator"></div>
			
		</script>
		<!-- Displaying Menu title name-->
		<script type="text/html" id="techMenuTemplate">
			<h4 data-bind="text:name"> </h4>
			<div class="menu-content-override" data-bind="template:{name:'topicListTemplate', foreach:topiclist, as:'topic'}">
			</div>
		</script>
	    <script type='text/javascript' src='js/menucontainerviewmodel.js'></script>
	</head>
        
         <div id="menu-container"> 
                <div class="menu-content" id="menu-list" data-bind="template:{name:'techMenuTemplate', foreach: techlists, as: 'tech'}">
                </div>
         </div>
        
</html>

 

To make the left navigation dynamic, we have created JSON file which contains information such as name, topiclist array which in turns contain topic name, page (which will open in the content section of the main page), breifdesc (if you want to add any description), and id to identify each menu item uniquely. To add new topic, you have to just add the data in this JSON file. 

To make things more dynamic, you can use database to store all these information.

The structure of JSON file will look like below as mentioned in the allarticles.json file.

allarticles.json

{
	"topiclists": [
		
		{
			"name": "Java",
			"topiclist": [{
				"topicname": "Regular Expression",
				"page": "views/java/regex.html",
				"breifdesc": "",
				"id": "regex"
			}]
		},
		   {
			"name": "JavaScript",
			"topiclist": [{
				"topicname": "ECMA",
				"page": "views/javascript/ecma.html",
				"breifdesc": "",
				"id": "ecma"
			}, {
				"topicname": "Progressive Pattern",
				"page": "views/javascript/progressive.html",
				"breifdesc": "",
				"id": "progressive"
			}, {
				"topicname": "BOM/DOM",
				"page": "views/javascript/dombom.html",
				"breifdesc": "",
				"id": "dombom"
			}, {
				"topicname": "Scopes",
				"page": "views/javascript/scopes.html",
				"breifdesc": "",
				"id": "js"
			}, {
				"topicname": "Initialization",
				"page": "views/javascript/initialization.html",
				"breifdesc": "",
				"id": "scopes"
			}, {
				"topicname": "Method Chaining",
				"page": "views/javascript/method-chaining.html",
				"breifdesc": "",
				"id": "method-chaining"
			}, {
				"topicname": "Object Creation",
				"page": "views/javascript/obj-creation.html",
				"breifdesc": "",
				"id": "obj-creation"
			}, {
				"topicname": "Callback Function",
				"page": "views/javascript/callback.html",
				"breifdesc": "",
				"id": "callback"
			}, {
				"topicname": "Anonymous Function",
				"page": "views/javascript/anonymous.html",
				"breifdesc": "",
				"id": "anonymous"
			}, {
				"topicname": "Closure",
				"page": "views/javascript/closure.html",
				"breifdesc": "",
				"id": "closure"
			}, {
				"topicname": "Bubbling & Capturing",
				"page": "views/javascript/bubblingcapturing.html",
				"breifdesc": "",
				"id": "bubblingcapturing"
			}, {
				"topicname": "OOPs in JavaScript",
				"page": "views/javascript/oops.html",
				"breifdesc": "",
				"id": "oops"
			}, {
				"topicname": "Bind Method",
				"page": "views/javascript/bind.html",
				"breifdesc": "",
				"id": "bind"
			}, {
				"topicname": "Call and Apply",
				"page": "views/javascript/callandapply.html",
				"breifdesc": "",
				"id": "callandapply"
			}]

		}, {
			"name": "Other",
			"topiclist": [{
				"topicname": "Delicious",
				"page": "views/other/delicious.html",
				"breifdesc": "",
				"id": "delicious"
			}, {
				"topicname": "Job Interview",
				"page": "views/other/job-interview.html",
				"breifdesc": "",
				"id": "job-interview"
			}, {
				"topicname": "Blog",
				"page": "views/other/blogs.html",
				"breifdesc": "",
				"id": "blogs"
			}]
		}
    ]

}

 

So in the above JSON file, we have created three topics Java, JavaScript and Other. Now in coming steps let's understand how we can read this information for displaying the accordion in left navigation section.

We are loading allarticles.json file in menucontainerviewmodel.js this file also contain logic for handling css (i.e. changing menu selection color on hover).

menucontainerviewmodel.js

var menuModel = {};
/*
 Here we are reading the json file.
*/
 $.getJSON("data/allarticles.json", function(data) { 
        /* creating techlists property of menuModel object and making it observable 
	array with help of knockoutjs library.
		*/
        menuModel.techlists = ko.observableArray(data.topiclists);
		/* Here we are just bindung the menuModel to the menu-container div, 
		which is in home.html*/
        ko.applyBindings(menuModel, document.getElementById("menu-container"));
		 $(function() {
			 	$( "#menu-list" ).accordion({
				collapsible: true,
				heightStyle: "content"
				});
		});
		
		  $('.menu-content-title').hover(
				
               function () {
                  $(this).css({"background-color":"#00131a"});
               }, 
				
               function () {
		 if($(this).attr("clicked") != 'true')
		 $(this).css({"background-color": "#00384d;"});
               }
            );	
 });
 

 

I am using another JS file (navhadling.js) for handling the css logic (i.e. activating the link which is selected and loading default and other page on click of the particular menu item).

navhandling.js

 function navlink(id, path){
	$('#container-example').load(path); //load the page
	// handling css logic
	$(".menu-content-title").removeClass("active-link");
	$(".menu-content-title").css({"background-color": "#00384d;"});
	$(".menu-content-title").removeAttr("clicked");
	$("#"+id).removeAttr("style");
	$("#"+id).addClass("active-link");
	$("#"+id).attr("clicked", "true");
	$(window).scrollTop(0);
}

 $( document ).ready(function() {
	// loading menu and default page.
	  $( "#left-nav" ).load("left-nav.html");
	  $( "#header-nav" ).load("header.html");
	  $( "#container-example" ).load("views/about.html");
  });  

 

In menucontainerviewmodel.js we are binding menuModel to "menu-container" div created in left-nav.html

And in left-nav.html code you can see I have defined two template one for rendering the Technology name (i.e. techMenuTemplate) and another (i.e. topicListTemplate) for displaying the topic list.

So as I explained about I how I am displaying the header information, it has been done in the similar manner.

That's all about knockoutJS template binding.

Source Code: KnockOutTemplateExample 

Please feel free to comment and ask questions.

Reference:
http://knockoutjs.com/documentation/introduction.html
http://learn.knockoutjs.com/
http://knockoutjs.com/examples/

Add a comment

Progressive vs Graceful Degration

 

In Graceful degration developer develop software for more advance version of browser, but also ensure that it should function properly on older browser version. 

So Progressive enhancement and Graceful degration altogether is a different concept. Progressive enhancement's main focus is on content, layer separation between structure, presentation and behavior, whereas Graceful degration's main focus is the browser. 

So if your software supports newer version and as well as older version of browser then it means your software is following the Graceful degration methodology.

If your website's more focus is on content and has layer separation (i.e. structure, presentation and behavior) and your website support newer and older versions of browser then you are following both methodologies in your application.

 

 

 

Add a comment

Understanding bind method

 

In this article we will understand bind method. Bind method used for currying (Currying is like a function returning closure function) functions and setting this value.

What is Currying? https://en.wikipedia.org/wiki/Currying

What is currying in JavaScript http://stackoverflow.com/questions/36314/what-is-currying

So let’s start

bind() method

bind() method allow us to bind specific object to function’s 'this' value. As we discussed above it is used for setting this value explicitly. It also helps you in borrowing methods. The use of bind() function is to create a new function (bound function).

Syntax: fun.bind(thisArg[, arg1[, arg2[, ...]]])

thisArg

The value to be passed as 'this' parameter to the target function when the bound function is called. The value is ignored if the bound function is constructed using the new operator.

arg1, arg2, ...

Arguments to prepend to arguments provided to the bound function when invoking the target function.

Before understanding bind, call and apply you must have better understanding of this keyword in JavaScript. Nice post for understanding 'this' keyword (http://javascriptissexy.com/understand-javascripts-this-with-clarity-and-master-it/ ).

 

Setting this Value using bind() method

So in this example we will see how bind method is used in setting this value explicitly.

 

Setting this value explicitly using bind().
<!DOCTYPE html>
<html>
    <head>
      
      <title>bind methods</title>
     <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js">
     </script>

    </head>
    <body>
       <div id="divbind" onclick="personInfoOnclick.showDetailsOnClick();" 
       style="height:10px; display:block;"> Show Information </div>
    </body>
	  <script type="text/javascript" src="callapplyandbind.js"></script>
	 
</html>
var personInfoOnclick = {
	info:{
	       firstName:"Deepak",
	       lastName:"Singh",
	       address:"Pune"
	},

       showDetailsOnClick:function(event){
	       console.log(this.info.firstName+" "+this.info.lastName+" "+this.info.address);
	}
};

/**
Here click event is bound to DOM element div and so the context of 'this' 
belongs to the div element and because of that it is not able to find 'info' 
property in 'this' context.
*/
// TypeError: this.info is undefined
$("#divbind").click(personInfoOnclick.showDetailsOnClick); 

/**
So to fix the above issue there are different ways.
*/

//Step 1. Use of bind() method to set the this value explicitly
$("#divbind").click(personInfoOnclick.showDetailsOnClick.bind(personInfoOnclick));
// Step 2. is passing annonymous callback function
$("#divbind").click(function(event) {
	personInfoOnclick.showDetailsOnClick(event);
});
// step 3. call method showDetailsOnClick from DOM element.
//onclick="personInfoOnclick.showDetailsOnClick();"
/*<div id="divbind" onclick="personInfoOnclick.showDetailsOnClick();" 
style="height:10px; display:block;"> Show Information </div>
*/
var info = {
	       firstName:"Rajveer",
	       lastName:"Singh",
	       address:"Pune"
}

var personInfoOnclick = {
	info:{
	       firstName:"Deepak",
	       lastName:"Singh",
	       address:"Pune"
	},

       showDetailsOnClick:function(event){
	       console.log(this.info.firstName+" "+this.info.lastName+" "+this.info.address);
	}
};

var showDetailsOnClickVar = personInfoOnclick.showDetailsOnClick;

showDetailsOnClickVar(); // Rajveer Singh Pune 

// Why it is printing Rajveer Singh why not Deepak Singh?

/**
This is because showDetailsOnClickVar is now a global function and context of this 
keyword belongs to global scope.

If variable 'info' was not defined as a global varaible and then you will try 
to call showDetailsOnClickVar() function as above then you will get JavaScript Error 
TypeError: this.info is undefined, because 'this.info' belongs to 
personInfoOnclick object locally and showDetailsOnClickVar() will try to find 'info' 
property in global 'this' which is undefined.

This can be fixed using bind() method by setting the this value       explicitly 
(i.e. passing personInfoOnclick object explicitly).
*/

var showDetailsOnClickVar = personInfoOnclick.showDetailsOnClick.bind(personInfoOnclick);

showDetailsOnClickVar(); // Deepak Singh Pune 

 

Borrowing with bind()

bind() also used for borrowing methods from other objects. Although it is always better to borrow methods using apply method. 

var personInfoOnclick = {
	info:{
	       firstName:"Deepak",
	       lastName:"Singh",
	       address:"Pune"
	},

       showDetailsOnClick:function(event){
	       console.log(this.info.firstName+" "+this.info.lastName+" "+this.info.address);
	}
};

// How to use the concept of borrow using bind
var dispOtherInfo = {
	info:{
	       firstName:"Jon",
	       lastName:"Smith",
	       address:"Cincinnati"
	}
}

dispOtherInfo.showDetailsOnClick = personInfoOnclick.showDetailsOnClick.bind(dispOtherInfo);
// Jon Smith Cincinnati
dispOtherInfo.showDetailsOnClick(); 

 

Partially applied functions (Currying)

bind() method is used for currying a functions. In brief currying in JavaScript is an ability to apply function partially (i.e. you can pass subset of the argument and get function and then pass rest of the parameter to get the final result when needed).

Let's see the example how bind method can help you in currying functions. 

function suggestActivity(age, temp, name){
	var msg = "";
	if(age < 10)
	       msg = "but in Guardian supervision";

       if(temp>=80){
	       console.log("Hey "+name+", You can Swim "+msg);
	}else if(temp >=60 && temp < 80){
	       console.log("Hey "+name+", You can play game like (Baseball, Tennis etc.) "+msg);
	}else if(temp >=40 && temp < 60){
	       console.log("Hey "+name+", You can Play Cricket or golf "+msg);
	}else if(temp < 40){
	       console.log("Hey "+name+", You can do Skiing "+msg);
	}
}

// first parameter is this, since we are not using 'this' keyword hence passing as a null
suggstActivityforAdlt = suggestActivity.bind(null, 30);

suggstActivityforAdlt(80, "Deepak Singh");
// Now you have to simply change the temprature and name to know the suggested activity.
suggstActivityforAdlt(60, "Jon");
suggstActivityforAdlt(50, "Richard");
suggstActivityforAdlt(38, "Tony");

suggstActivityforKid = suggestActivity.bind(null, 8);

suggstActivityforKid(80, "Dhiraaj");
// Now you have to simply change the temprature and name to know the suggested activity.
suggstActivityforKid(60, "Rajveer");
suggstActivityforKid(50, "Tom");
suggstActivityforKid(38, "Angela");

 

Hope you have got fare understanding of bind() method in JavaScript.

 
Keep Reading and Keep Learning.
 

Reference: MSDN bind() function

Add a comment

Call and apply

Call and apply methods are very frequently used methods in JavaScript and both function allow us in setting this value explicitly, borrowing functions from other object.

The only difference between Call and apply is the way we pass parameters to them.

In call method we pass arguments individually (i.e. named set of parameters) whether in apply we pass arguments as an array which is more useful in case of executing variable-arity functions.

variable-arity functions are known as variadic functions. These functions accept any number of arguments.

The Math.max() is a common example of variable-arity function.

We can pass any number of arguments to this function.

Console.log(Math.max(78,29,22,89,98));//98

Or you can pass array of numbers instead of passing N number of arguments.

var argArray = [78,29,22,89,98];

Console.log(Math.max(argArray));//98

Note: Wherever call method is used in example apply method can also be applied there. As you know the only difference between call and apply is the way we pass parameters.

Setting this value

 Let's understand this by simple example. 

 
var roots=0;

function getSquareRoots(numbers){
	this.roots = numbers.map(Math.sqrt);
}

var data = {
	numbers: [4, 9, 16],
	roots:0
}

// Simple call will set roots value to global 
// 'roots' variable (i.e. in roots variable in window scope)
getSquareRoots(data.numbers);
console.log(data.roots); // 0

console.log(window.roots); //[2,3,4]

// so to set roots value of data object we can use call or apply method.

getSquareRoots.call(data, data.numbers);
console.log(data.roots); //[2,3,4]
// Similarly you can use apply method as well. 
// The only difference is I am passing the parameter as an array.
getSquareRoots.apply(data, [data.numbers]);
console.log(data.roots); //[2,3,4]

 

Used for Chaining Constructor

Call and apply method used for chaining constructor, which is useful for implementing prototypical Inheritance in JavaScript. To see how to implement Inheritace in JavaScript refer OOP's in JavaScript.

Let's see the example

 

 function Shape(name, color) {
    this.name = name;
    this.color = color;

    return this;
}
Shape.prototype.displayShape = function (){
    console.log("Name : "+this.name+" color: "+this.color);
}
function Rectangle(name, color) {
// Here we are using call method for chaining constructor
    Shape.call(this, name, color); 
// Added extra property to different shapes.
    this.sides = '4';
}
// Create a Rectangle.prototype object that inherits from Shape.prototype.
// Note: A common error here is to use "new Shape()" to create the
// Rectangle.prototype. The correct place to call Shape is above, 
// where we call t from Rectangle. 
// Similarly other shapes object created and Inherited from Shape class.
Rectangle.prototype = Object.create(Shape.prototype);
Rectangle.prototype.constructor = Rectangle; // Reset the constructor from Shape to Rectangle
Rectangle.prototype.changeColor = function (colr){
    this.color = colr;
    console.log("Color Changed for "+this.name);
}
function Triangle(name, color) {
// you can use apply for chaining the constructor.
    Shape.call(this, name, color);
    this.sides = '3';
}
Triangle.prototype = Object.create(Shape.prototype);
Triangle.prototype.constructor = Triangle; // Reset the constructor from Shape to Triangle
Triangle.prototype.changeColor = function (colr){
    this.color = colr;
    console.log("Color Changed for "+this.name);
}
function Circle(name, color) {
    // you can use apply also for chaining the constructor. 
    // The only difference is the way we pass parameter.
    Shape.call(this, name, color);
    this.sides = '0';
}
Circle.prototype = Object.create(Shape.prototype);
Circle.prototype.constructor = Circle; // Reset the constructor from Shape to Circle

Circle.prototype.changeColor = function (colr){
    this.color = colr;
    console.log("Color Changed for "+this.name);
}
var rect = new Rectangle('Rectangle', 'red');
var tri = new Triangle('Triangle', 'Blue');
var cir = new Circle('Circle', 'Green');

rect.displayShape(); //Name : Rectangle color: red
tri.displayShape(); // Name : Triangle color: Blue
cir.displayShape();// Name : Circle color: Green
rect.changeColor("blue") //Color Changed for Rectangle
rect.displayShape(); //Name : Rectangle color: blue
tri.changeColor("Green") //Color Changed for Triangle
tri.displayShape(); //Name : Triangle color: Green
cir.changeColor("Red") //Color Changed for Circle
cir.displayShape(); //Name : Circle color: Red
 

 

In the above example apply method set this value to callbackObj. Which allow us to execute the callback function with this value set explicitly and the parameter passed to the callback function will be set on 'formatName' object.

 

Call and apply method can be used for calling anonymous functions.

 

Use for Borrowing functions

call and apply method used for borrowing functionalities from other objects. For example we can borrow Array's useful functionality in array-like object. For example you can use push, pop and other methods of an Array object.

 

An array-like object is an object that has its key defined as non-negative integers.

 Let's understand this by example also add a 'length' property in array-like object, so that we can relate an array-like object to an array object.

 

 
var arrayLikeObj = {0:"Deepak", 1:"Singh", 2:"35", length:3};
var newArray = Array.prototype.slice.call(arrayLikeObj, 0);
console.log(newArray);
// You can use push method.
Array.prototype.push.call(arrayLikeObj, 'Cincinnati');
// You can notice here the length of the object got changed.
console.log(arrayLikeObj); //{0:"Deepak", 1:"Singh", 2:"35", 3:"Cincinnati" length:4}
// You can do search as well.
var index = Array.prototype.indexOf.call(arrayLikeObj, 'Cincinnati');
console.log(index); // 3
// You can use pop, reverse and other methods to get the benefits 
// of Array functions in an array-like objects.

 

More frequent use of call and apply methods are for extracting the parameter passed to JavaScript functions from an arguments object which is property of all JavaScript functions and is an array-like object.

 For Example: 

function list(){
    console.log(arguments);
    return Array.prototype.slice.call(arguments, 0);
}
console.log(list(1,2,3,4,5)); //[1, 2, 3, 4, 5]
console.log(list("UP", "MH", "BH", "HY")); // ["UP", "MH", "BH", "HY"]

 

Hope you have got fare understanding of call and apply method in JavaScript.

Keep Reading and Keep Learning.

References:

MSDN call() function

MSDN apply() function

http://javascriptissexy.com/javascript-apply-call-and-bind-methods-are-essential-for-javascript-professionals/

Add a comment

Event Bubbling & Capturing

 

Let's talk about interesting topic Event bubbling & capturing in JavaScript. If you never heard about this, then now you are going to get this right now right away ;)

 
Event Bubbling up
 
DOM elements can be nested, and clicking on inner (child) element will invoke handler of parent element. This is called bubbling up. 
 
Event Bubble up Example 1
  • List 1
  • List 2
  • List 3
/**
As you can see here, even clicking on "<li>" child element,
parent element's "<ul>" handler (i.e. onclick event get fired) 
also getting called.
*/
<ul onclick="alert('<ul> clicked')">
	<li onclick="alert('<li> clicked')"> List 1 </li>
	<li onclick="alert('<li> clicked')"> List 2 </li>
	<li onclick="alert('<li> clicked')"> List 3 </li>
</ul>

 

This is happening because an event bubbles up from nested (child) element and triggers the parent element handlers. You can think of event bubbling is like ripple effect when you drop an object in water (you can see ripple effect in below image). The event gets triggered from inner towards outer element.

 

 

Let's visualize this with another example.

 

Event Bubble up Example 2
    • List 1
    • List 2
    • List 3
/**
So when you click on inner li element, 
the handler of outer elements are also getting called.
And the order of execution will be like this if you click 
on any of the li : three->two->one
*/
<html>
<head>
	<title>Event Bubbling Example</title>
	<link rel="stylesheet" type="text/css" href="eventbubble.css">
</head>
<body>
<ul class="one" onclick="changeColor(this)">
  <ul class="two" onclick="changeColor(this)">
	<li class="three" onclick="changeColor(this)">
		List 1
	</li>
	 <li class="three" onclick="changeColor(this)">
		List 2
	 </li>
	 <li class="three" onclick="changeColor(this)">
		List 3
	 </li>
   </ul>
 </ul>
</body>
</html>
<script >
function changeColor(_this){
	_this.style.backgroundColor = 'Chartreuse';
	alert(_this.className);
	_this.style.backgroundColor = '';
}
</script>

 


 

Capturing
 
So What is Capturing? The event first goes down is called capturing phase, and then bubble up.
As per the above example (Example 2) Execution order will be as below for Capturing and bubbling up.
 
Capturing phase: one->two->three
Bubble up phase: three->two->one
 
You can enable event capturing only by passing last parameter as true (phase) to addEventListener method (i.e element.addEventListener(type, handler, phase);)

phase = true : handler is set on the capturing phase.
phase = false: handler is set on bubbling phase.
 
Target vs this
 
target is going to be the same originating element (i.e. the element where you have performed any event). this is current element, it changes in context of current element. Let's understand this by example, I am taking the same example 2.
 
 
Target vs this Example
    • List 1
    • List 2
    • List 3
/**
So if you see here target element is not changing (it's consistent) and 
this is changing as per the current element handler execution.
*/
<html>
<head>
	<title>Event Bubbling Example</title>
	<link rel="stylesheet" type="text/css" href="eventbubble.css">
</head>
<body>
<ul class="one" onclick="changeColorWithEvnt(this, event)">
  <ul class="two" onclick="changeColorWithEvnt(this, event)">
	<li class="three" onclick="changeColorWithEvnt(this, event)">
		List 1
	</li>
	 <li class="three" onclick="changeColorWithEvnt(this, event)">
		List 2
	 </li>
	 <li class="three" onclick="changeColorWithEvnt(this, event)">
		List 3
	 </li>
   </ul>
 </ul>
</body>
</html>
<script >
function changeColorWithEvnt(_this, event){
	_this.style.backgroundColor = 'Chartreuse';
	alert("This: "+_this.className);
	alert("Target: "+event.target.className);
	_this.style.backgroundColor = '';
}
</script>

 


 

Stop Bubbling up
 
You can stop event bubbling simply by calling event.stopPropagation() method. For IE < 9 it is event.cancelBubble = true.
Let's take the same example again.
 
 
Cancel Bubble up
    • List 1
    • List 2
    • List 3
/**
So if you see here target element is not changing (it's consistent) and 
this is changing as per the current element handler execution.
*/
<html>
<head>
	<title>Event Bubbling Example</title>
	<link rel="stylesheet" type="text/css" href="eventbubble.css">
</head>
<body>
<ul class="one" onclick="cancelBubbleup(this, event)">
  <ul class="two" onclick="cancelBubbleup(this, event)">
	<li class="three" onclick="cancelBubbleup(this, event)">
		List 1
	</li>
	 <li class="three" onclick="cancelBubbleup(this, event)">
		List 2
	 </li>
	 <li class="three" onclick="cancelBubbleup(this, event)">
		List 3
	 </li>
   </ul>
 </ul>
</body>
</html>
<script >
function cancelBubbleup(_this, event){
	event.stopPropagation(); // this cancel the bubble up event.
	_this.style.backgroundColor = 'Chartreuse';
	alert("This: "+_this.className);
	alert("Target: "+event.target.className);
	_this.style.backgroundColor = '';
}
</script>

 

Hope you have got fare understanding of Event Bubbling and Capturing in JavaScript.
 
 
Keep Reading and Keep Learning.
Add a comment