Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Alertify with return from confirm

I'm trying to use alertify.js as a confirmation dialog for all my confirm scripts. But it just isn't working like regular JS confirm does. In the code below I never get a return true

function aConf ( mes ) {
    alertify.confirm( mes, function (e) {
        return e;
    });
}

<a href="#" onclick="if(aConf(\'Are you sure you wish to remove this?\')) { function(); } return false;">Delete</a>

Of course if I replace aConf with JS' confirm it works. So why is alertify not sending me back it's outcome?

like image 552
jfreak53 Avatar asked Jan 18 '13 22:01

jfreak53


1 Answers

Because confirm is a blocking function (no javascript will run until it returns true/false), and alertify is non-blocking (JS keeps executing). Alertify does not immediately return a true/false, but instead, it probably returns undefined immediately, then it calls a callback function later, after the user clicks OK or Cancel. The return value from that callback function has no effect in your example, because the onclick code has already finished running (because it is non-blocking).

Assuming you are using this: https://github.com/fabien-d/alertify.js/

This is how it actually works with a callback function, not a return value:

alertify.confirm( message, function (e) {
    if (e) {
        //after clicking OK
    } else {
        //after clicking Cancel
    }
});

For your code sample, you might try something like this:

function performDelete ( a_element ) {
    // perform your delete here
    // a_element is the <a> tag that was clicked
}

function confirmAction ( a_element, message, action ) {
    alertify.confirm(message, function(e) {
        if (e) {
            // a_element is the <a> tag that was clicked
            if (action) {
                action(a_element);
            }
        }
    });
}

<a href="#" onclick="confirmAction(this, 'Are you sure you wish to remove this?', performDelete); return false;">Delete</a>

EDIT: updated to be a generic confirm dialog that calls a callback function if the user clicks ok.

like image 100
Levi Avatar answered Sep 28 '22 09:09

Levi