I have a code like this where I am trying to add an event handler to some button. I would like to use a global variable & store its current value in callback closure & not its reference.
var globalNum="dummy";
function A()
{
$("#button").click(function()
{
$("#button").append(globalNum);
});
}
globalNum="dummyAgain";
Now if click event is fired what would be added – “dummy” or “dummyAgain” ?
I believe it would be “dummyAgain” coz for closure global variable’s reference is stored. I want value to bind.
I know I can create a local variable inside A which I can initialize with global variable & bind that but is there some other cooler way around too?
Thanks
You are right, it would append dummyAgain. You can deal with this by using
bind()and send some event data:Note that I immediately execute the function
A, so the click handler gets attached before the value ofglobalNumchanges. As @Andrew points out in his comment, this is the same effect as not using the “wrapping” functionAat all.Same solution without
bind:Here the anonymous function is useful to capture the the current value
globalNumin a local variable.Update:
For the sake of completeness (I hope, @Andrew, you don’t mind that I put it here). The “coolest” way is probably to use a parameter for the function and execute the function immediately with this parameter:
The “trick” is that the name of the parameter and the name of the global variable are the same.
This is also very often used to refer to some object with a shorter identifier without polluting the global namespace, e.g. with jQuery: