1

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

3
  • What about creating a copy of the value when the event listener is added? Commented Mar 1, 2012 at 17:39
  • It has to be static as a number of buttons will be created. Commented Mar 1, 2012 at 17:41
  • the script is right when will alert "b" and not "a", because by the time the user clicks, foo has already value "b"; what you got there with addEventListener is you assign a function to that event, so when event is triggered the function is executed Commented Mar 1, 2012 at 17:51

2 Answers 2

7

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/

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.