tags:

views:

3931

answers:

3

The situation is somewhat like-

var someVar; 
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.

Thanks in advance.

A: 

There is absolutely nothing wrong with the code you've written. Both some_function and someVar should be accessible, in case they were available in the context where anonymous function(){some_function(someVar);} was 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 to addEventListener)

var someVar; 
someVar = some_other_function();
alert(someVar);
someObj.addEventListener("click",
                         function(){
                          some_function(someVar);
                         },
                         false);

Sergey Ilinsky
+1  A: 

someVar value should be accessible only in some_function() context, not from listener's. If you like to have it within listener, you must do something like:

someObj.addEventListener("click",
                         function(){
                             var newVar = someVar;
                             some_function(someVar);
                         },
                         false);

and use newVar instead.

The other way is to return someVar value from some_function() for using it further in listener (as a new local var):

var someVar = some_function(someVar);
Thevs
A: 

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 parameter funcName is the function name variable

You can remove the listener with myaudio.removeEventListener('ended',func,false);

Ganesh Krishnan