我有一个jquery移动对话框,用于确认用户是否要覆盖他们上传的文件。如果用户单击是,则调用要上载的回调函数,如果他们单击否,则关闭对话框并且没有任何反应。
问题在于,如果用户单击否,然后再次单击上载并接受覆盖,则会调用两次回调函数。它正在构建回调,具体取决于它们进入对话状态的时间,我不知道如何处理它。
每次用户点击“上传”时,这都是入口点
CheckOverwriteUpload: function (boxFolderId, fileName) {
var matchFound = false;
$.each(BoxManager.Entries, function (index, value) {
var entry = value;
if (entry.name == fileName) {
matchFound = true;//Found the matching file
}
})
if (matchFound) {
//Pop the dialog to ask if they want to overwrite the file
areYouSure("Overwrite File?", "The file " + fileName + " Already exists, would you like to overwrite it?", "Yes", function (result) {
if (result == true) {
//The client wants to overwrite the file, so we upload it
BoxManager.UploadFile(boxFolderId, fileName, true);
} else {
//The client does not want to overwrite. Close the dialog
$("#sure").dialog('close');
}
//Placed here to close the dialog after the possible upload
$("#sure").dialog('close');
});
} else {
//No matches, go ahead and upload
BoxManager.UploadFile(boxFolderId, fileName, matchFound);
}
},
这是对话功能
function areYouSure(text1, text2, button, callback) {
$("#sure .sure-1").text(text1);
$("#sure .sure-2").text(text2);
$("#sure .sure-do").text(button).on("click", function () {
callback(true);
});
$("#sure .close-do").text("No").on("click", function () {
callback(false);
});
$.mobile.changePage("#sure", 'none', false, true);
}
以防万一需要,这是上传代码。它只是在服务器上调用一个方法
UploadFile: function (boxFolderId, fileName, overWrite) {
$.mobile.showPageLoadingMsg();
var etag = "";
var id = "";
$.each(BoxManager.Entries, function (index, value) {
var entry = value;
if (entry.name == fileName) {
etag = entry.etag;//hash of file used to overwrite files on box.com
id = entry.id;//unique box id for file. needed to overwrite file
}
});
DocumentVaultService.UploadFileToBox(
"<%=RootFolderGuid %>",
"<%=FolderGuid %>",
"<%=FileGuid %>",
boxFolderId,
fileName,
"<%=IsClientFolder%>",
"<%=AuthToken %>",
overWrite,
etag,
id,
function (result) {
//Success on the upload, refresh the document list and close loading symbol
BoxManager.GetBoxFolderContent(boxFolderId, BoxManager.BreadCrumbList[length - 1].folderName);
$.mobile.hidePageLoadingMsg();
},
function (result) {
$.mobile.hidePageLoadingMsg();
alert("File failed to upload");
});
}
CheckOverwriteUpload和UploadFile都包含在Boxmanager中,如此
var BoxManager = {
CheckOverwriteUpload:function(){},
UploadFile:function(){}
}
如何防止此次呼叫多次?有没有办法在调用对话框之前清除javascript缓存?是否有一个更好的结构,我没有看到回调?
答案 0 :(得分:0)
每次调用areYouSure()
时,它都会再次绑定回调。解决这个问题的一种方法是取消绑定,然后绑定:
$("#sure .close-do").text("No").unbind("click").on("click", function () {
callback(false);
});
注意unbind("click")
。这将删除任何先前的绑定,因此它们不会叠加
另一种方法是将Yes / No按钮绑定放在其他只调用一次的地方(如pageinit
)。
答案 1 :(得分:0)
确保不要将同一事件多次绑定到同一个按钮。
此外,在绑定事件时添加命名空间,这样您也不会意外取消绑定其他点击事件。
$('button').off('click.box-manager').on('click.box-manager', function(e){
...do something
});
除非你确定没有人会在你的按钮上分配一个事件,否则这是非常的。