Search code examples
javascriptjqueryfunctioncallbackjquery-callback

jQuery callback function accumulating


I wrote some code for a custom confirm box that calls a function when confirm button (yes-button) is pressed and passes another function as a parameter and I bind it to 2 different button clicks with different functions as a parameter. For example:

$('#button1').click(function() {
    callFunction(function() { alert("test"); });
});
$('#button2').click(function() {
    callFunction(function() { alert("test2"); });
});

function callFunction(callback) {
    //code to display custom confirm box

    console.log(callback);

    $('.confirm-box .yes-button').click(function() {
        callback();
    });
}

Everything happens as expected, confirm box appears and on confirm button click I get a callback function executed and it alerts "test" (or "test2" depending on which button called the confirm box). The problem arises when I click button1 that sends a function that alerts "test", then instead of confirming I cancel that (nothing happens as expected), and then click button2 that passes alert("test2") as a callback function. Now once I press the yes-button instead of alerting just "test2", I get both "test2" and "test" alerts even though that console.log I wrote logs just the function that alerts "test2" at the time of that button2 click. It seems like these callback functions get stacked somewhere, but I don't understand where and why.


Solution

  • The .click() function can add more than one handler to an element, and I think that's what's happening here. Try this:

    // ...
    $('.confirm-box .yes-button').unbind('click').click(function() {
        callback();
    });
    

    This removes any previous click handler before applying the new one.