Skip to content Skip to sidebar Skip to footer

Event Handler For Click Event Fires Automatically - JQuery

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

Solution 1:

Actually here

btn.click(bindClick(btn)); 

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

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's lok at 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 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()


Solution 2:

The problem is :

btn.click(bindClick(btn));

It will call the bindClick method. Try to change that line with this and see if the behavior if same with JavaScript#2:

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

Or more simpler :

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

Post a Comment for "Event Handler For Click Event Fires Automatically - JQuery"