The situation is somewhat like-
var someVar = some_other_function();
someObj.addEventListener("click", function(){
some_function(someVar);
}, false);
The problem is that the value of someVar
is not visible inside the listener function of the addEventListener
, where it is probably being treated as a new variable.
Why not just get the arguments from the target attribute of the event?
Example:
JavaScript is a prototype-oriented language, remember!
You need:
someVar
value should be accessible only insome_function()
context, not from listener's. If you like to have it within listener, you must do something like:and use
newVar
instead.The other way is to return
someVar
value fromsome_function()
for using it further in listener (as a new local var):Quite and old question but I had the same issue today. Cleanest solution I found is to use the concept of currying.
The code for that:
By naming the curried function it allows you to call Object.removeEventListener to unregister the eventListener at a later execution time.
Use
And if you want to pass any custom value into this anonymous function then the easiest way to do it is
Works perfectly in my project. Hope this will help