jQuery jqModal confirm dialog callback issue
Using the code from the jqModal website, section FUN! Overrides:
http://dev.iceburg.net/jquery/jqModal/#examples (I edited the code to make use of a callback function)function confirm(msg,callback) {
$('#confirm')
.jqmShow()
.find('p.jqmConfirmMsg')
.html(msg)
.end()
.find(':submit:visible')
.click(function(){
if(this.value == 'yes')
(typeof callback == 'string') ?
window.location.href = callback :
callback();
$('#confirm').jqmHide();
});
}
$().ready(function() {
$('#confirm').jqm({overlay: 88, modal: true, trigger: false});
// trigger a confirm whenever links of class alert are pressed.
$('a.confirm').click(function() {
confirm('About to visit: '+this.href+' !',callbackfunction);
return false;
});
});
function callbackfunction()
{
console.log("callback triggered");
}
The problem: each time when the confirm function is called, the callback gets triggered incrementally, so when I click the 2nd time, t开发者_运维知识库he handler gets executed 2 times, the 3th time, 3 times and so on.
This happens because each time you call the confirm function, you add a new 'click' event handler.
The solution is simply unbinding the click event in the confirm box before binding the new, updated callback. In my example below, note the confirm() function and the unbind of any bound click events before binding the new callback. Perhaps his example code should really be:
function confirm(msg,callback) {
$('#confirm')
.jqmShow()
.find('p.jqmConfirmMsg')
.html(msg)
.end()
.find(':submit:visible')
.unbind('click')
.click(function(){
if(this.value == 'yes')
(typeof callback == 'string') ?
window.location.href = callback :
callback();
$('#confirm').jqmHide();
});
}
Some time has past since your original post but perhaps this can be of use to someone in the future. jqModal is really quite great.
精彩评论