jquery click handler fires multipli times
Im having trouble that 开发者_运维知识库my saveBtn click events fire multipli times because the function below is called and registering a new click handler for each time the user calls the function. How do i only register one click event handler?
function forceAnnotation(annotationNo,objectNo,clientNo, callBack) {
$('#forcedAnnotation').dialog( {
modal: true,
width: 385,
height: 370,
closeOnEscape: false,
open: function(event, ui) { jQuery('.ui-dialog-titlebar-close').hide(); }
});
$('#cancelBtn').click(function() {
callBack.onCancel();
$('#forcedAnnotation').dialog("close")
});
$('#saveBtn').click(function(){
//make ajax call
});
}
Maybe you could use the jQuery.one() function.
"Attach a handler to an event for the elements. The handler is executed at most once per element."
http://api.jquery.com/one/
If you are forced to add the click handler every time why not just detach it every time also with:
$('#cancelBtn').unbind('click');
To make sure you just unbind this specific click handler you can use namespaces.
$('#cancelBtn').unbind('click.annotation').bind('click.annotation', function(e) {
callBack.onCancel();
$('#forcedAnnotation').dialog("close")
});
$('#saveBtn').unbind('click.annotation').bind('click.annotation', function(e) {
//make ajax call
});
This should work, I hope
The easiest way would be to refactor your code to remove the click
handler registration to be outside of the function.
If that is not possible, you could declare the cancel function outside of the scope of your forceAnnotation()
function. And in your function redefine it to be what you need.
var cancelClick = function(){};
function forceAnnotation(annotationNo,objectNo,clientNo, callBack) {
$('#forcedAnnotation').dialog( {
modal: true,
width: 385,
height: 370,
closeOnEscape: false,
open: function(event, ui) { jQuery('.ui-dialog-titlebar-close').hide(); }
});
cancelClick = function(){
callBack.onCancel();
$('#forcedAnnotation').dialog("close");
}
}
$('#cancelBtn').click(function() {
cancelClick();
});
$('#saveBtn').click(function(){
//make ajax call
});
Other options are, .one()
Attach a handler to an event for the elements. The handler is executed at most once per element.
Or to simply unbind()
the click handler each time.
$('#cancelBtn').unbind("click").click(function() {
callBack.onCancel();
$('#forcedAnnotation').dialog("close")
});
精彩评论