Make use of Javascript wisely

Posted: Saturday, June 18, 2011 by Unknown in Labels:

In javascript, We can write programs in very optimized manner as we can send functions as arguments or as return values. Here is a small snippet of code where we can avoid repeat work.

function addHandler(elem, event, handler){
if(elem.addEventListener){ // DOM2
addHandler = function(elem, event, handler){
elem.addEventListener(event, handler, false);
}else{ // IE
addHandler = function(elem, event, handler){
elem.attachEvent("on" + event, handler);

addHandler(elem, event, handler);

During addHandler fist call the function definition varied.

Enhanced by Zemanta