I am opening a modal dialog this way:
let myModal = new bootstrap.Modal('#myModal', {
keyboard: false,
backdrop: 'static'
});
#myModal
has a button in it which I bind click event to in the modal shown
event.
$('#myModal').on('shown.bs.modal', event => {
$('#btnMyButton').on('click', function ()
{
console.log('Was clicked!');
});
});
And when I close the modal, I am unbinding the event:
$('#myModal').on('hidden.bs.modal', event => {
$('#btnMyButton').off('click');
$('#myModal').off('show.bs.modal');
$('#myModal').off('shown.bs.modal');
$('#myModal').off('hidden.bs.modal');
myModal.dispose();
console.log('hidden here!');
})
The problem is that, when I first show the modal dialog and press the button, click
event is called once.
If I close the dialog and open it again. Click event is called twice, and so on.
How can I correctly unbind the click event? Why myModal.dispose()
does not unbind events automatically?
Don't register a new handler each time the model pop-up opens. put handler code outside as well as use event delegation like below:
myModal.on('click','#btnMyButton', function (){
console.log('Was clicked!');
});