Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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/

like image 539
Habibillah Avatar asked Dec 04 '22 08:12

Habibillah


2 Answers

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');
    });

});
like image 176
Jeff Sisson Avatar answered Dec 06 '22 22:12

Jeff Sisson


You can call one() against on():

$('#general_modal .action_button').unbind().one('click', function () {

According to documentation:

The .one() method is identical to .on(), except that the handler for a given element and event type is unbound after its first invocation. For example:

http://jsfiddle.net/kJn47/47/

like image 27
Marcelo Amorim Avatar answered Dec 06 '22 22:12

Marcelo Amorim