2

I am using bootbox for confirm alert box that I alert to user. It is called from one js file and I have a common function where it is created. How can I use callback function to get the result of the confirm dialog box:

So my js is as below:

 var message = "Do you want to close?";

 loadConfirmAlert(message);
 if (result) {
     //do stuff
 }

The loadCofirmAlert function in another js file then is as below:

var loadCofirmAlert = function (message) {

    bootbox.confirm(message, function (result) { });
}

what I am unsure off is how to pass this result value back to the calling function?

Ctrl_Alt_Defeat
  • 3,933
  • 12
  • 66
  • 116

2 Answers2

3

Try it like this

var message = "Do you want to close?";

loadConfirmAlert(message,function(result){
    if (result) {
        //do stuff
    }
});

var loadCofirmAlert = function (message,callback) {
    bootbox.confirm(message, function (result) { 
        callback&&callback(result);
    });
}

UPDATE

Where

callback&&callback(result)

Is just a shorter version of

if (callback)callback(result); //if callback defined, call it

You can also use checking if callback is a function by using

(typeof(callback)==="function")&&callback(result)
Jevgeni
  • 2,556
  • 1
  • 15
  • 18
1

You have to put that if statement inside of the callback

bootbox.confirm(message, function (result) {
    if (result) {
        //do stuff
    }
});

The problem you're facing is that your loadConfirmAlert(message); is not setting any global variable called result and so in your first code snippet, result is never filled.

Your problem is very well described in here How do I return the response from an asynchronous call? (although he is mentioning it with ajax, but you're having essentialy the same problem)

Community
  • 1
  • 1
leopik
  • 2,323
  • 2
  • 17
  • 29
  • the if statement though contains fields that I hide specific to the page where I am calling the loadCofirm so I really want to pass the result back to that page? – Ctrl_Alt_Defeat Oct 02 '14 at 10:01
  • @Ctrl_Alt_Defeat then take a look at mentioned [$.Deferred](http://api.jquery.com/category/deferred-object/) or send `callback` function as second parameter to `loadCofirmAlert` as jevgenig has suggested. – Regent Oct 02 '14 at 10:03