Event handler for click event fires automatically - jQuery

Possible duplicate:
Why click event handler right after page load?

There is a gap in my understanding of the Javascript function, so it is difficult for me to understand why my event handlers are 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 click event 
});

function bindClick(source){
    console.log('get here');
}

      

+3


source to share


2 answers


Actually here

btn.click(bindClick(btn)); 

      

you just bind the return value of the function to the click event and not to the function itself.
Since in javascript you can return a function, this will work

var btn = $('#change-html');
btn.click(bindClick(btn));

function bindClick(source){
    return function() {
        console.log('get here');
    }    
}

      

http://jsfiddle.net/VZ4Gq/



EDIT - is the second function a closure? Yes, it might be .Let lok in this example

var btn = $('#change-html');
btn.click(bindClick(btn));
// global scope
var inside = "i'm outside a closure";
console.log(inside);
function bindClick(source){
    // local scope 
    var inside = "i'm inside a closure";
    return function() {
        console.log(inside);
    }   
}

      

http://jsfiddle.net/VZ4Gq/1/

when you try to do this, you first register me behind closure, and then when you click the button you get me inside closure. this is because you actually created a closure and a function, when it executes, it executed the original scope in it, which is inside bindClick ()

+6


source


The problem is this:

btn.click(bindClick(btn));

      

It is called by the bindClick method. Try changing this line with this and see if the behavior is the same if it matches JavaScript # 2:



btn.click({param1: btn }, bindClick);

      

Or more simply:

btn.click({param1: btn }, $(this));

      

+1


source







All Articles