0

I am trying to create a function like window.confirm which can be used like this :

if (I.confirmDialog.open("Do you really want to Cancel")) {
    // do this
} 
else { 
    //  do this 
}

I am writing the pop-up function like this :

I.confirmDialog = {

  open: function(confirmMsg) {

    var $modal = I.modals.new("small confirm-dialog");
    $modal.find("h1").text(confirmMsg);
    $modal.append("<div class=\"action-wraper\"><a class=\"action-yes\" href=\"javascript:void(0);\">Yes</a><a class=\"action-no\"href=\"javascript:void(0);\">No</a></div>");
    I.modals.open($modal);
    $modal.find(".action-yes").click(function() { I.modals.close(); /* return true will not work*/ });
    $modal.find(".action-no").click(function() { I.modals.close(); /* return false will not work*/ });

  }

};

But the problem is I am unable to return true or false from the I.confirmDialog.open(). execution of I.confirmDialog.open() function doesn't wait for button click and the return from click callback doesn't affect the return value of I.confirmDialog.open().

I would like to know how window.confirm is written if possible

Tripurari Shankar
  • 3,308
  • 1
  • 15
  • 24
  • jQuery Promises https://api.jquery.com/promise/ – AndFisher Dec 23 '16 at 12:11
  • As far as I know it is not possible to create a modal dialog from javascript. Basically you have to rely on the click event callbacks. Also a transparent full-page div could be used to simulate the modal behavior preventing user interaction with the other page elements. – al01 Dec 23 '16 at 12:14

1 Answers1

2

The issue you have here is that the modal being actioned is effectively asynchronous (as you have to wait for user input), so you cannot return anything.

Instead, provide some callback functions to the method which can be called in the required events:

I.confirmDialog = {
    open: function(confirmMsg, yesCallback, noCallback) {
        var $modal = I.modals.new("small confirm-dialog");
        $modal.append('<div class="action-wraper"><a class="action-yes" href="#">Yes</a><a class="action-no" href="#">No</a></div>').find("h1").text(confirmMsg);

        I.modals.open($modal);

        $modal.find(".action-yes").click(function(e) { 
            e.preventDefault();
            I.modals.close(); 
            yesCallback && yesCallback();
        });

        $modal.find(".action-no").click(function(e) { 
            e.preventDefault();
            I.modals.close(); 
            noCallback && noCallback();
        });
    }
};

You would then call it like this:

I.confirmDialog.open("Do you really want to Cancel", function() {
    console.log('you clicked YES');
}, function() {
    console.log('you clicked NO');
});
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339