I’m trying to understand how variable scope works when you bind an event.
The following example works fine:
function clickHandler() {
alert(foo);
}
var foo = true;
$('div').on({
'click': clickHandler
});
See: http://jsfiddle.net/OliverJAsh/7fM5U/4/
However, when I make this simple change, it doesn’t work anymore:
function clickHandler() {
alert(foo);
}
(function () {
var foo = true;
$('div').on({
'click': clickHandler
});
}());
See: http://jsfiddle.net/OliverJAsh/7fM5U/3/
How would you go about making the second example work? Can I do anything with .call? I am wondering this because the function is being called where the variable is defined, so I want it to have access to that.
UPDATE:
I understand why it can’t access the variable – but because the function is being called from where the variable is defined, I wondered how I could make it work, without moving the scope of things. I think I’m asking about the .call method.
In javascript variables are scoped within functions – so the scope of foo is within your anonymous
(function () { .. }());which is not visible toclickHandler.To fix it you can bring the
clickHandlerfunction into the anonymous function like so:Update
If you are unable to change the scoping if the clickHandler function and do not wish to change the signature either, you can use the
callfunction like so: