You are right, it would append dummyAgain. You can deal with this by using bind()
and send some event data:
var globalNum="dummy";
(function A()
{
$("#button").bind('click', {localNum: globalNum}, function(e)
{
$("#button").append(e.data.localNum);
});
})();
globalNum="dummyAgain";
Note that I immediately execute the function A
, so the click handler gets attached before the value of globalNum
changes. As @Andrew points out in his comment, this is the same effect as not using the "wrapping" function A
at all.
Same solution without bind
:
(function()
{
var localNum = globalNum;
$("#button").click(function()
{
$("#button").append(localNum);
});
})();
Here the anonymous function is useful to capture the the current value globalNum
in 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:
var globalNum="dummy";
(function(globalNum)
{
$("#button").click(function()
{
$("#button").append(globalNum);
});
})(globalNum);
globalNum="dummyAgain";
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:
(function($) {
// jQuery == $
})(jQuery)