Javascript pass values to function on event listener

2.2k views Asked by At

If I do the following the variable is passed to the attached event listener where as I want the value of the variable at the time the event listener is added passed.

foo=a;    
document.addEventListener('mousedown', function() { doSomething(foo) }, false); 
foo=b;

doSomething(val){
alert(val);
}

so it should alert "a" not "b";

2

There are 2 answers

0
Yoshi On BEST ANSWER

something like:

var foo = 'a';    

document
.getElementById('foo')
.addEventListener('click', function(bar) {

  // return the actual event handler function
  return function() {
    doSomething(bar);
  };

}(foo) /* <-- call the anonymous function, passing in the current foo*/, false); 

foo = 'b';

function doSomething (val) {
  alert(val);
}​

demo: http://jsfiddle.net/gS9wu/1/

0
MyStream On

Since foo is global, then foo is overwritten on line 3 before the event is detected.

You may want to consider fetching the value of foo and storing it on an object or in a plugin or similar to abstract it away from your normal code flow or to pass it into the callback function:

document.addEventListener('mousedown',(function(outerFoo){ doSomething(outerFoo); })(foo), false);