Search code examples
jquerytwitter-bootstrapmodal-dialognestedpropagation

Nested jQuery onClick event handler fires multiple times


Using a bootstrap modal, i want to register an event-handler both for the modal and the following submit-button inside this modal.

Invoking the modal and closing ist subsequently leads to multiple execution of the #modalSubmitButton event. Could you think of any solution to prevent that behaviour and only fire on the actual event, ignoring previous invocations of the modal ? Is my approach of nesting the handlers maybe wrong ?

I already tried all combinations of event.stopPropagation / event.unbind(), etc.

$(document).on('click', '#myModalID' function () {

    // i fetch some data from the clicked element here
    //  and make it accessible to the subsequent eventHandler

        $(document).on('click', '#modalSubmitButton' function () {

            // eventually calling service on click of button
            invokeService()
    });
});

Solution

  • Simple fix: don't nest event handlers. With the implementation of delegated event handlers (which you're already using) there is no need to.

    $(document).on('click', '#myModalID' function () {
        // i fetch some data from the clicked element here
        //  and make it accessible to the subsequent eventHandler
    });
    
    $(document).on('click', '#modalSubmitButton' function () {
        // eventually calling service on click of button
        invokeService()
    });