Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

shown.bs.modal fires multiple times when you close and reopen modal

I have made a fiddle illustrating the issue I am facing at the moment. So every time I close and open a modal, shown.bs.modal also fires multiple times. In this fiddle, every time you close and open a modal, number of alerts also increases (when it's supposed to trigger only once). http://jsfiddle.net/j36h2/1/

function openTestModal(){
    $('#testModal').modal({
        keyboard: false,
        backdrop: 'static'
    });

    $('#testModal').on('shown.bs.modal', function (e) {
        alert('');
    });
}

$('.testButton').click(function(){
    openTestModal();
});
like image 571
pewpewlasers Avatar asked Jan 09 '14 09:01

pewpewlasers


2 Answers

or you can try this :

$('#testModal').on('shown.bs.modal', function (e) {
 alert('');
 $(this).off('shown.bs.modal');
});
like image 50
ilan weissberg Avatar answered Sep 21 '22 02:09

ilan weissberg


The accepted answer from @Put12co22mer2 is correct. However, there are times when you want to rebind the event when opening the modal. Let's say you got some options that should be used.

function openTestModal(options){
    $('#testModal').modal({
        keyboard: false,
        backdrop: 'static'
    });

    $('#testModal').one('shown.bs.modal', function (e) {
        // do something with options
        alert(options.foo);
    });
}

$('.testButton').click(function(){
    openTestModal({ foo: bar});
});

Then you can use one instead of on. The result will be the same as unbinding, but a bit cleaner in my opinion.

http://api.jquery.com/one/

The .one() method is identical to .on(), except that the handler is unbound after its first invocation

like image 21
smoksnes Avatar answered Sep 21 '22 02:09

smoksnes