Monday, November 21, 2011

Hack for functions inside loop in Javascript


In one of my earlier blogs, I had mentioned that is not advisable to create functions inside a loop in Javascript, as any strict environment will result in an error in the JS file, such as a JsLint installation.

I had also cited an alternative approach to call a function inside the loop, instead of creating it inline.

But in some cases, it becomes imperative to have this functionality and even calling the function is not helpful.

Consider this piece of code


var obj = [ { a: ".link1", b: ".div1", c: ".div2"},
{ a: ".link4", b: ".div3", c: ".div4"},
...
];

for( var i = 0; i < obj.length; i++) { 

 var o = obj[i]; 
 $(o.a).click(function(e) { 
    e.preventDefault(); // some more operations... 
 }); 
}






Basically the obj stores a list of objects and on click event of each, we want the divs in 'b' & 'c' to be hidden or shown etc.


Now, the anonymous function inside the click event is being created number of times, because of being in the loop.


The style mentioned in the (previous blog) won't work because one cannot capture the event in 'e' with this syntax.

for(var i = 0; i < obj.length; i++) {
  var o = obj[i];
  $(o.a).click = externalFunction(e, object);
}


So we do a hack in fooling JSLint by calling the function inside the loop itself, and avoiding its complaining like this.

$.each(obj, function(index, object) {
  $(object.a).click(function(e) {
    e.preventDefault();
    // some more operations...
  });
});


There have to be 2 parameters in the each's first parameter as the each method generates 2 objects - index of the object being operated on, and the object itself.


No comments:

Post a Comment