I use the following function to bind all members of a certain class to a function that changes the current page. Heres the function:
function _bind_menu_items() {
var menuItems = fja.getElementsByClass("menuItem"),
index,
elementID,
divIdToBind;
for (index in menuItems) {
elementID = menuItems[index].id;
divIdToBind = elementID.replace("Item", "");
menuItems[index].onclick = function() {
fja.menu.changeActivePage(divIdToBind);
};
}
}
I’ve checked that everything works as expected down to the actual assignment of the onclick property. The error I’m getting is that every div belonging to the menuItem class seems to call the same onclick function… as if the divIdToBind string is the exact same for every onclick that is assigned… How can I fix this?
Number one mistake for Javascript beginners. you’re missing that the anonymous functions which gets bound to your
onclickhandler, closes over its parent context. Since all closures from the same parent context share the same scope chain, all of this functions will reference the last value which gets passed intodivIdToBind.To solve that issue, the most common workaround is to create another function(-context):
Now we do create another function which gets executed immediately. We pass it in the value from
divIdToBindand all it does is to return another function (just to create a new context)