I have this problem:
I have defined an event handler which requires parameters on it.
var handler = function(p1, p2){
//some code
}
Then I add the event handler to an object inside a function.
function foo(p1, p2){
//Some code
obj.addEventListener('click', handler(p1, p2), false)
}
As you already know the code above is not correct. It wont listen to the event. Instead it will execute the function instantly. Now to fix this I can just erase handler(p1, p2) and insert function(){ handler(p1, p2) } instead. But the problem is that I have an another function that I want to remove the event listener, which is not possible with the latter solution.
function koo(){
//Some code
obj.removeEventListener('click', handler, false)
}
How do I fix this?
I think you’ll need to create a closure:
…and now you can assign the handler like so, while still having access to p1 and p2:
Note that
handleris now a global variable.Update: I just realized that in your case, this could be simplified by merging
createHandlerandfooas follows: