gpt4 book ai didi

JavaScript 异步回调

转载 作者:行者123 更新时间:2023-12-02 20:21:00 24 4
gpt4 key购买 nike

我的问题在代码中得到了更好的解释:

//This code is triggered before ajax ObBegin. But I need f1 to return a boolean to either cancel or continue the event.
f1();

function f1(){
$.modalWindow.Open(); //This is an async method, this is where my problem lies.
//I need to freeze here and wait on a return value from one of the events below.
}

//In the modal window:

//An event which waits for the click event
$('.cancelBtn').click(function(){
//How do I send false back to f1?
closeModalWindow();
});

$('.yesBtn').click(function(){
//How do I send true back to f1?
closeModalWindow();
});

所以基本上发生的事情是这样的:

  1. openModalWindow() 打开一个等待按钮单击的模式窗口。
  2. 我想将值传递回 f1 并返回它。

有办法解决这个问题吗?

最佳答案

使用 jQuery 的 Deferred objects 。有一个很好的教程here ,但您实际上没有向我展示足够的您自己的代码来演示如何将其与 $.Deferred 连接起来。

<小时/>

以下是如何执行此操作的非常基本的演示:http://jsfiddle.net/mattball/fNQ8J/ 。基本上,您必须传递回调以异步执行。

function openModalWindow(callback) {
if (typeof callback !== 'function') callback = $.noop;
$("#dialog-confirm").show().dialog({
resizable: false,
modal: true,
buttons: {
Yes: function() {
$(this).dialog("close");
callback(true);
},
No: function() {
$(this).dialog("close");
callback(false);
}
}
});
}

function f1() {
return $.Deferred(function(dfd) {
openModalWindow(dfd.resolve);
}).promise();
}

$('#clickme').click(function() {
f1().then(function(result) {
alert('f1 async returned: ' + result);
});
});

关于JavaScript 异步回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5560932/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com