How to do early binding for event handler in JavaScript? (example with jQuery)
- by Sven Larson
JavaScript's late binding is great. But how do I early bind when I want to?
I am using jQuery to add links with event handlers in a loop to a div. The variable 'aTag ' changes in the loop. When I click the links later, all links alert the same message, which is the last value of 'aTag'. How do I bind a different alert message to all links?
All links should alert with the value that aTag had when the event handler was added, not when it was clicked.
for (aTag in tagList) {
if (tagList.hasOwnProperty(aTag)) {
nextTag = $('<a href="#"></a>');
nextTag.text(aTag);
nextTag.click(function() { alert(aTag); });
$('#mydiv').append(nextTag);
$('#mydiv').append(' ');
}
}