Possible Duplicate:
Why does click event handler fire immediately upon page load?
There is a gap in my understanding of Javascript’s function so I have trouble understanding why my event handlers get fired automatically if I define it without an anonymous wrapper.
HTML
<a href="#" id="change-html">Change HTML</a>
Javascript #1
var btn = $('#change-html');
btn.click(bindClick(btn)); // bindClick gets executed right away and only once
function bindClick(source){
console.log('get here');
}
Javascript #2
var btn = $('#change-html');
btn.click(function(){
bindClick(btn); // bindClick is only executed on the anchor's click event
});
function bindClick(source){
console.log('get here');
}
Actually here
you are just binding the return value of the function to the click event, not the function itself.
Since in javascript you can return a function this would work
http://jsfiddle.net/VZ4Gq/
EDIT – is the second function a closure?Yes it might be.Let’s lok at this example
http://jsfiddle.net/VZ4Gq/1/
when you try this you get logged “i’m outside a closure” first and then when you click on the button you get “i’m inside a closure”. this is because you actually created a closure and the ffunction, when it’s executo, it’s executed in it’s original scope, which is inside bindClick()