Guesser
Guesser

Reputation: 1857

Javascript pass values to function on event listener

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";

Upvotes: 1

Views: 2264

Answers (2)

Yoshi
Yoshi

Reputation: 54649

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/

Upvotes: 7

MyStream
MyStream

Reputation: 2553

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);

Upvotes: 0

Related Questions