I would like to pass an argument to a callback function inside a for loop. The problem is the callback is called after the for loop ends and then the parameter does not exist anymore.
See the following code snippet:
function foo(x){
console.log(x)
}
for(var i = 0; i < arr.length; i++) {
var myObj = customObject()
myObj.on('click', function(){
foo(arr[i])
}
}
myObj
is clicked on after the for loop ends which triggers an error:
TypeError: arr[i] is undefined
Is there any way to force the argument to be passed by its value at time of binding the callback function?