HTML and CSS Reference
In-Depth Information
if (regexp.test(anchors[i].className)) {
anchorLightbox(anchors[i]);
}
}
}());
6.2.1.2 Simulating Block Scope
Another useful case for immediately called closures is when creating closures inside
loops. Assume that we had opted for a different design of our lightbox widget,
in which there was only one object, and it could be used to open any number
of lightboxes. In this case we would need to add event handlers manually, as in
Listing 6.12.
Listing 6.12 Adding event handlers the wrong way
(function () {
var anchors = document.getElementsByTagName("a");
var controller = Object.create(lightboxController);
var regexp = /(^ | \s)lightbox(\s | $ )/;
for(vari=0,l=anchors.length; i < l; i++) {
if (regexp.test(anchors[i].className)) {
anchors[i].onclick = function () {
controller.open(anchors[i]);
return false;
};
}
}
}());
This example will not work as expected. The event handler attached to the links
forms a closure that can access the variables local to the outer function. However,
all the closures (one for each anchor) keep a reference to the same scope; clicking
any of the anchors will cause the same lightbox to open. When the event handler
for an anchor is called, the outer function has changed the value of i since it was
assigned, thus it will not trigger the correct lightbox to open.
To fix this we can use a closure to capture the anchor we want to associate with
the event handler by storing it in a variable that is not available to the outer function,
and thus cannot be changed by it. Listing 6.13 fixes the issue by passing the anchor
as argument to a new closure.
 
Search WWH ::




Custom Search