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.
You can just bind all necessary arguments with 'bind':
In this way you'll always get the
event
,arg1
, and other stuff passed tomyPrettyHandler
.http://passy.svbtle.com/partial-application-in-javascript-using-bind
I was stuck in this as I was using it in a loop for finding elements and adding listner to it. If you're using it in a loop, then this will work perfectly
You could pass somevar by value(not by reference) via a javascript feature known as closure:
Or you could write a common wrap function such as
wrapEventCallback
:Here
wrapEventCallback(func,var1,var2)
is like:You can add and remove eventlisteners with arguments by declaring a function as a variable.
myaudio.addEventListener('ended',funcName=function(){newSrc(myaudio)},false);
newSrc
is the method with myaudio as parameterfuncName
is the function name variableYou can remove the listener with
myaudio.removeEventListener('ended',func,false);
There is absolutely nothing wrong with the code you've written. Both
some_function
andsomeVar
should be accessible, in case they were available in the context where anonymouswas created.
Check if the alert gives you the value you've been looking for, be sure it will be accessible in the scope of anonymous function (unless you have more code that operates on the same
someVar
variable next to the call toaddEventListener
)This solution may good for looking
or bind valiables will be also good