Search code examples
javascriptjqueryfunctioncallbackuser-defined

User-defined callback function is being fired multiple times in Javascript/jQuery


There are some similar questions, but they all seem like regarding native jQuery callback functions.

So I have this code which (live) creates a div containting some form elements. Values of these elements should be retrieved inside a callback function when (before) the div is removed.

function popup(callback) {
    // ...
    // before removing the div
    callback.call();

    // remove div
}

Unexpectedly, the callback function is being fired multiple times (increasingly) after the first time popup is executed.

I have simplified the code, and here is the fiddle.


Solution

  • I hope this is what you need.

    function popup(callback) {
        $("body").append('<div><span id="test">test</span> <a href="#" id="close">close</a></div>');
        $(document).on("click", "#close", function() {
            callback.call();
    
            //
            //callback = function() {};
            $(document).off("click", "#close");
            $("div").remove();
    
        });
    };
    
    $(document).on("click", "#open", function() {
        popup(function() {
            alert('$("#test").length = ' + $("#test").length);
        });
    });
    

    Basically, you need to remove event handler by invoking off() method.