3

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?

1
  • Or you can use $.Deferred. Commented Oct 2, 2014 at 10:01

2 Answers 2

4

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)
Sign up to request clarification or add additional context in comments.

1 Comment

This works nicely - can you just explain the callback&&callback(result); syntax?
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)

2 Comments

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 then take a look at mentioned $.Deferred or send callback function as second parameter to loadCofirmAlert as jevgenig has suggested.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.