I’m relatively new to javascript and although I know what’s causing the bug, I’m not sure how to refactor this to make it work.
for ( ... ) {
var variableQueryValue = i
addLink.bind('click', function() {
$.ajax({
type: 'POST',
url: '/example',
data: 'queryvalue=' + variableQueryValue,
success: function(data) {
console.log('Got into success method!');
}
});
});
}
So basically we are binding a click event to some element whose data attribute is dependent on some variableQueryValue that changes every iteration. Because of the closure of the bind function handler, in the ajax request it will bind an event handler that uses the same value of variableQueryValue for each iteration.
How can I refactor this such that the updated variableQueryValue is taken into account?
Thanks for any help!
Invoke a function that creates your handler, passing
iinto that function. Then have that function return the handler to be assigned to the.bind('click',....This is because when you invoke a function, you create a new variable environment. So when you pass the value of
iinto the function, and create your handler inside that same function, your handler is now referencing the value that was passed into that specific variable environment.The handler will retain the original variable environment in which it was created (even though you’re returning the handler), so it will always reference the proper
ivalue.There are other solutions to the problem of retaining a persistent value used in a handler, but this resolves the specific closure issue. Depending on the actual situation, this may or may not be what you want to do.