Habibillah Habibillah - 3 months ago 40
Javascript Question

Callback function called twice and more on Bootstrap Modal

I have problem when create custom JQuery plugin that will show Bootstrap modal dialog. The custom plugin require callback function as it's parameter.

The problem are when modal dialog called twice, callback also called twice, and so on.

Here the code:

HTML

<a href="#" class="confirm_delete">test modal</a>

<div class="modal fade" id="general_modal" tabindex="-1" role="dialog" aria-labelledby="general_modalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
<h4 class="modal-title" id="general_modal_title">Set Title Here</h4>

</div>
<div class="modal-body">set modal content here</div>
<div class="modal-footer">
<button type="button" class="btn btn-default close_button" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary action_button">Save changes</button>
</div>
</div>
</div>




Javascript

(function ($) {
$.fn.showDialog = function (options, callback) {
$('#general_modal').modal();
$('#general_modal .action_button').on('click', function () {
callback();
});
}
}(jQuery));

$('.confirm_delete').click(function (e) {
e.preventDefault();
$(this).showDialog(null, function () {
alert('xxx');
});

});


DEMO: http://jsfiddle.net/kJn47/2/


Answer

You are rebinding the modal and click events each time showDialog is run. Here's how you might prevent the events being re-attached each time:

(function ($) {
    $.fn.showDialog = function (options, callback) {
        $('#general_modal').unbind().modal();
        $('#general_modal .action_button').unbind().on('click', function () {
            callback();
        });
    }
}(jQuery));

$('.confirm_delete').click(function (e) {
    e.preventDefault();
    $(this).showDialog(null, function () {
        alert('xxx');
    });

});