سؤال

I have a modal which content is dynamic, and this modal has a reject button.

This modal itself is generated dynamically via a link, so I have to use delegate

$( "body" ).delegate( ".reject", "click", function(e) {
     $(".modalInfo").hide();
     $(".modalReject").show();
     someFunction();
});

Let's say the user click on the reject button and close the modal. Then she loads a new modal, so this modal's context changing and has a new reject button.

The moment user click the reject button again on this new context, somehow someFunction() executed twice - once from the original click, and second one from this new click. Close the modal again, load a new context, execute the click and voila.. got three someFunction() calls!

After some research, this is what I found: When replace element, what happen on the events and data

How to prevent this?

هل كانت مفيدة؟

المحلول

First off, if your .reject buttons on all your dialogs all have the same behavior and class names, then you can just leave the one delegated event handler in place and you don't need to install it again or remove the prior one. The beauty of using delegated event handling is that the target objects can come and go and the event handler remains in place just fine.

If you do have a reason for removing the original event handler and replacing it with something else and if you switch to using .on() instead of .delegate() (the current way of doing things in jQuery 1.7+), then you can do it like this:

$(document.body).on("click", ".reject", function(e) {
     $(".modalInfo").hide();
     $(".modalReject").show();
     someFunction();
});

Then, you can uninstall the event handler with .off() like this:

$(document.body).off("click", ".reject");

Or, if you want to remove only a single delegated event handler for that event and selector, then you need to declare the function separately and then pass the same function to both .on() and .off().

function myHandler(e) {
    $(".modalInfo").hide();
    $(".modalReject").show();
    someFunction();
}

$(document.body).on("click", ".reject", myHandler);

Then, you can uninstall just that single event handler with .off() like this:

$(document.body).off("click", ".reject", myHandler);

FYI, .delegate() has been superceded by .on() since jQuery 1.7.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top