0

So, I wrote a function to emulate the functionality of JavaScript confirm box.

How to make a function not return until a specific task has been accomplished? Here mconfirm returns undefined. I want to return true or false based upon the user clicked Yes/Cancel. How could I do this?

var mconfirm = function(message) {
    if(!message)
        message = "Remove the selected item?";
    $("#dialog-confirm").html('<span class="glyphicon glyphicon-alert" id="confirm-alert-ico"></span>&nbsp;' + message);
    $( "#dialog-confirm" ).dialog({
          resizable: false,
          modal: true,
          buttons: {
            Yes: function() {
              $( this ).dialog( "close" );
              return true;
            },
            Cancel: function() {
              $( this ).dialog( "close" );
              return false;
            }
          }  
        });
};
Suhail Gupta
  • 22,386
  • 64
  • 200
  • 328

1 Answers1

1

You can not wait for such an operation to be finished before returning. (Closing a dialog is just as asynchronous as getting input from anywhere)

In JS you typically provide the user a way to pass a function that is called when the operation is done. (That is, pass a callback).

var mconfirm = function(message, callback) {
if(!message)
    message = "Remove the selected item?";
$("#dialog-confirm").html('<span class="glyphicon glyphicon-alert" id="confirm-alert-ico"></span>&nbsp;' + message);
$( "#dialog-confirm" ).dialog({
      resizable: false,
      modal: true,
      buttons: {
        Yes: function() {
          $( this ).dialog( "close" );
          // Pass whatever you want to the callback
          callback("yes");
          return true;
        },
        Cancel: function() {
          $( this ).dialog( "close" );
          // Pass whatever you want to the callback
          callback("cancel");
          return false;
        }
      }  
    });
};

And, instead of doing something like :

var result = mconfirm("Are you sure ?");
// result is "yes" or "cancel"

The caller would do

mconfirm("Are you sure", function(result) {
   // result is "yes" or "cancel"
});
phtrivier
  • 13,047
  • 6
  • 48
  • 79
  • But I need to return the state `true` or `false` when the user has clicked the button. The current code http://pastebin.com/6rTsvkMU won't allow this – Suhail Gupta Nov 23 '15 at 11:26
  • Yes, unfortunately, you'll have to change the structure of the code that opens the dialog. This is a general issue with asynchronous programming. See also this answer : https://stackoverflow.com/questions/6962301/change-the-asynchronous-jquery-dialog-to-be-synchronous – phtrivier Nov 23 '15 at 14:21