1

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.

user1643156
  • 4,407
  • 10
  • 36
  • 59

3 Answers3

1

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.

spiritwalker
  • 2,257
  • 14
  • 9
0

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/

Kevin Bowersox
  • 93,289
  • 19
  • 159
  • 189
0

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();
});
Salman
  • 9,299
  • 6
  • 40
  • 73
  • In the actual code, popup is called within another function, there are some other values that need to be passed to function popup. When the popup is closed, there are some generated data need to be passed back and dealt with. So it can't be that straight. Anyway, I'v got the answer from spiritwalker. – user1643156 Feb 12 '13 at 11:23