Question

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.

Was it helpful?

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.

OTHER TIPS

Try dynamically generating the elements instead of using a string. This will allow you to bind events easier.

function popup(callback) 
{   var $elem = $("<div></div>");
    $elem.append($("<span></span>").html("test"));
    $elem.append(" ");
    $elem.append($("<a></a>").html("close").attr("href", "#"));

    $("body").append($elem);
    $elem.find("a").click(function() {
        callback.call();  
        $elem.remove();
    });
};

$(document).on("click", "#open", function() {
    popup(function() {
        alert('$("#test").length = ' + $("#test").length);
    });
});

Example: http://jsfiddle.net/4se7M/2/

I don't know the exact scenario, but why do you want to bind and unbind the event each time you show the popup?

You can bind only once, like this, can't you?

$(document).on("click", "#close", function() {
    alert('$("#test").length = ' + $("#test").length);
    $("div").remove();
});

function popup() {
    $("body").append('<div><span id="test">test</span> <a href="#" id="close">close</a></div>');
};

$(document).on("click", "#open", function() {
    popup();
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top