Search code examples
javascriptjqueryconfirm

How to make a function not return until a specific task has been accomplished?


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;
            }
          }  
        });
};

Solution

  • 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"
    });