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.
Here's yet another way (This one works inside for loops):
Other alternative, perhaps not as elegant as the use of bind, but it is valid for events in a loop
It has been tested for google chrome extensions and maybe e.srcElement must be replaced by e.source in other browsers
I found this solution using the comment posted by Imatoria but I cannot mark it as useful because I do not have enough reputation :D
The following answer is correct but the below code is not working in IE8 if suppose you compressed the js file using yuicompressor. (In fact,still most of the US peoples using IE8)
So, we can fix the above issue as follows and it works fine in all browsers
Hope, it would be useful for some one who is compressing the js file in production environment.
Good Luck!!
This question is old but I thought I'd offer an alternative using ES5's .bind() - for posterity. :)
Just be aware that you need to set up your listener function with the first param as the argument you're passing into bind (your other function) and the second param is now the event (instead of the first, as it would have been).
Sending arguments to an eventListener's callback function requires creating an isolated function and passing arguments to that isolated function.
Here's a nice little helper function you can use. Based on "hello world's" example above.)
One thing that is also needed is to maintain a reference to the function so we can remove the listener cleanly.
The following code worked fine for me (firefox):
Output: