Javascript async callback
My problem is better explained in code:
//This code is triggered before ajax ObBegin. But I need f1 to return a boolean to either cancel or 开发者_如何学JAVAcontinue 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();
});
So basically what happens is this:
openModalWindow()
opens a modal window that waits on a button click.- I want to pass the value back to f1 and return it.
Is there a way to fix this?
Use jQuery's Deferred objects. There's a good tutorial on it here, but you haven't actually shown enough of your own code for me to demonstrate how to wire it up with $.Deferred
.
Here's a very basic demo of how to do this: http://jsfiddle.net/mattball/fNQ8J/. Basically, you have to pass callbacks around for asynchronous execution.
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);
});
});
There's no good way to do this, no. You'll have to refactor f1
so it can deal with asynchronicity.
f1()
should be implemented as a callback for someAsyncFunc()
:
function someAsyncFunc(callback) {
// open your modal window
$(".theBtm").click(function() {
// do your stuff
if (typeof(callback) === "function") {
callback(theValueYouWantToPass);
}
});
}
Called something like this:
someAsyncFunc(function(value) { f1(value); });
精彩评论