I’m trying to create a function that shows a modal dialog which when called blocks until the dialog is closed, this will allow for a result to be returned to the caller
The following function is an attempt which has two problems.
- It returns the result while the dialog is still open.
- The selector test does not find the dialog, inspecting with firebug reveals that the
idelement is lost once the dialog is created.
.
function getCountrySelection() {
var ctryCode;
var dlg = $("#JS-field-dlg-ctry-select");
if (dlg.size() === 0) {
dlg = $("<div id='JS-field-dlg-ctry-select' title='Select Country' class='dialog-fields'></div>");
dlg.append("Customer found in both Australia and New Zealand");
dlg.dialog({
autoOpen: false,
width: 400,
height: 160,
modal: true,
buttons: {
"Australia": function() {
ctryCode = "au";
$(this).dialog("close");
},
"New Zealand": function() {
ctryCode = "nz";
$(this).dialog("close");
},
"Cancel": function() {
$(this).dialog("close");
}
}
});
}
dlg.dialog('open');
return ctryCode;
}
EDIT: I thought I’d show how I’m calling this:
buttons: {
"Find": function() {
var custAu = JS.sales.getCustomer("au", inpCust.val());
var custNz = JS.sales.getCustomer("nz", inpCust.val());
var cust;
if (custAu === undefined && custNz === undefined) {
alert('No customer could be found with that number.');
return;
} else if (custAu !== undefined && custNz !== undefined) {
var ctry;
getCountrySelection(function(result) {
ct = result;
});
if (ctry === "au") {
cust = custAu;
} else if (ctry === "nz") {
cust = custNz;
} else {
return;
}
} else if (custNz === undefined) {
cust = custAu;
} else {
cust = custNz;
}
if (cust) {
$(this).dialog("close");
// Do something with cust.
} else {
alert('Customer could not be found.');
}
},
"Cancel": function() {
$(this).dialog("close");
}
}
There is no way to block execution until the dialog closes; JavaScript does not allow to “suspend” execution. Your best bet is to change the contract of your function; instead of returning the value straight away, it should accept a callback function that it will call with the result as soon as the dialog is dismissed. Then the code calling this will provide a suitable callback in which it can continue its execution.
Something like this:
Then use:
This is basically the same thing as with AJAX calls; you can’t “suspend” your AJAX call to wait until the AJAX actually completes and returns the result, hence “asynchronous”.
EDIT: In your specific example, you could use it like this: