Many of the times we need to attach event iterating over loop of components but we need to pass some dynamic value which should be available when actually listener is called.
For example, we are iterating over list of buttons and attaching event listener of click event but want to pass current index when click event is actually called
We try something like this,
var buttons = $('input[type=button]');
for (var i = 0, n = buttons.length; i<n; i++) {
var button = buttons[i];
button.addEventListener('click', function() {
buttonClick(i, button); // i, el will have last updated values
});
}
function doSomethingWith(i, button){
console.log("i: " +i + " " + "button: "+button);
}
Above code won’t work because the function is actually created once (instead of each iteration of the loop) and that one function points to the last known values of the variables it uses.
Each callback expects one handler instance or function. Now lets create function and return function with proper variables so with each iteration function returns brand new function with proper value defined. So each callback have different instance of function value with appropriate value
Below is the sample
(function(variable) {
return function() {
// do something with variable
}
})(value);
Let us examine above sample
There are two function: an outer and an inner. The inner function that contains your original code. The outer function is wrapped in parenthesis and passes some “value”. This means that the inner function can use the identifier “variable” and it will refer to whatever value was passed to it. So with each iteration, outer function is called with value passed in and returns instance of inner function as handler.
Lets use this in above sample,
$(document).ready(function(){
var buttons = $('input[type=button]');
for (var i = 0, n = buttons.length; i<n; i++) {
var button = buttons[i];
button.addEventListener('click', (function(i, button) {
return function() {
buttonClick(i, button);
}
})(i, button));
}
});
function buttonClick(i, button){
console.log("i: " +i + " " + "button: "+button);
}
Test the sample and see with each click to button, you will get different value for i and el
Hope this helps!!!