Reputation: 3575
I use twitter bootstrap modals's js to show and hide a modal:
$('#myModal').modal('show')//show
$('#myModal').on('shown', function () {
// do something…
})
$('#myModal').on('hidden', function () {
// do something…
})
....
$('#myModal').modal('hide')//hide
My problem is when show and hide modal multiple times, the code in //do something...
run multiple times. I guess that's because every time i show a modal, it listen to shown
and the function run 5 times when the modal hide and open 5 times, any way to prevent this?
Using the way fco
suggested below did solve the shown problem, but unfortunately the hide does not work, i.e. still execute more than one times, one thing different, i hide the dialog using the data-dismiss="modal"
markup, not through js.
Any ideas?
Upvotes: 2
Views: 5306
Reputation: 2405
You should use one instead of on
The .one() method is identical to .on(), except that the handler is unbound after its first invocation. For example:
$('#myModal').modal('show')//show
$('#myModal').one('shown', function () {
// do something…
})
$('#myModal').one('hidden', function () {
// do something…
})
....
$('#myModal').modal('hide')//hide
Upvotes: 3
Reputation: 883
check out .off()
if you want the event handler to run only the first time you need to do something like:
function myHandler() {
//your event handling code here
$('#myModal').off('show', myHandler);
}
$('#myModal').on('shown', myHandler);
$('#myModal').modal('show');
//...
$('#myModal').modal('hide');
Upvotes: 2