I’m trying to bind functions to items in a node list in Internet Explorer 7.
for(var j = 0; j < navLabels.length; j++)
{
navInsets[j].onmouseover = function(){showLabel(navLabels[j], true);};
navInsets[j].onmouseout = function(){showLabel(navLabels[j], false);};
navInsets[j].onclick = function(){selectNew(j);};
navLabels[j].onclick = function(){selectNew(j);};
}
showLabel() and selectNew() are each my own functions. They each need to be passed an index which, in this case, is j.
I know that, inside the anonymous functions, j will end up being a reference to j, not the value of j. I also know that I could use the addEventListener or the bind methods to do this, but neither is allowed in IE 7. I even know that the attachEvent method would work for ie7, but since I need to pass arguments, I would need to wrap the functions in an anonymous function to use attachEvent (at least that’s what appears to be true), which is the original problem.
Any not-too-hacky thoughts on the subject? Thanks.
You don’t necessarily need to use an IIFE for each bound event. You can use the same captured
jin all event bindings:I don’t think you can get any “cleaner” than that. You might be able to extract the anonymous function and make it a named function (in the same scope as
navInsetsandnavLabels), but that could make it hard to see what the loop actually does (since you have to go lookup the one-use function). I don’t see any obvious other solutions, since you will need a closure anyhow.