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.