我用 jq 替换了标准确认对话框。
我允许用户传入一个函数,如果用户单击“确定”,该函数将被调用。
传入的函数可能会调用长时间运行的异步任务,例如 ajax 调用,有时不会,我想同时满足两者。
我使用此解决方案作为基础 ( https://stackoverflow.com/a/19374933 )
我想要实现的是这样的:
MyConfirmation('A Title', 'A message to the user', function() {
$.get('/some/bigdata/longrunning');
}
).then(function() {
// add to dom here
});
这是我的确认:
MyConfirmation = function (title, message, ok) {
var d = $.Deferred();
$('<div/>')
.text(message)
.dialog({
buttons: {
"Ok": function () {
if($.isFunction(ok)) {
ok.apply();
}
$(this).dialog("close");
d.resolve(true);
return true;
},
"Cancel": function () {
$(this).dialog("close");
d.resolve(false);
return false;
}
},
close: function(event, ui) {
$(this).remove();
},
resizable: false,
draggable: false,
width: 'auto',
title: title,
modal: true
});
return d.promise();
};
我想理想地与我的 deferred 结合起来,它返回 true 或 false 来指示用户是否单击了“确定”或“取消”。
我知道我可以对从 $.get 返回的 promise 使用 .done 方法,但是我如何使我的解决方案发挥作用
最佳答案
I am allowing the user to pass in a function that will be called if the user clicks on ok.
不要。只需从 MyConfirmation
函数中删除该 ok
参数,并且仅返回按钮点击的 promise 。如果用户愿意,则可以将其功能链接到该功能上,或者执行更多操作。
您的调用应该如下所示:
MyConfirmation('A Title', 'A message to the user').then(function(okPressed) {
if (okPressed)
return $.get('/some/bigdata/longrunning');
}).then(function(longruningResult) {
// add to dom here
});
当按下Cancel按钮时,您也可以reject()
promise ,那么您就不需要 bool okPressed
检查和可以使用单独的错误处理程序来代替。
关于jQuery 包装延迟和 promise ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21723878/