How to do early binding for event handler in JavaScript? (example with jQuery)

Posted by Sven Larson on Stack Overflow See other posts from Stack Overflow or by Sven Larson
Published on 2010-04-18T19:20:44Z Indexed on 2010/04/18 19:23 UTC
Read the original article Hit count: 590

Filed under:
|
|

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(' ');
  }
}

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about earlybinding