Search code examples
jqueryjquery-uiconfirm-dialog

JQuery confirmation dialog


I am looking for an way to implement a reusable "confirm" Dialog with JQuery..

This is the part from the MyApp Class to open the dialog:

/**
 * @param text string Message to display
 */
getConfirmationDialog: function(text) {
   MyApp.confirmDialog = $('<div><p>' + text + '</p></div>');
   MyApp.confirmDialog
    .dialog({
        modal: true,
        autoOpen: false,
        title: 'Please confirm',
        width: 300,
        height: 180,
        buttons: {
            'OK': function() {
                return true;
            },
            Cancel: function() {
                $(this).dialog('close');
                return false;
            }
        }
    });

    MyApp.confirmDialog.dialog('open');
},

In another class I do:

/**
 * Clear system cache
 *
 * @param url string Backend URL
 */
clearCache: function(url) {

    dialog = MyApp.getConfirmationDialog('Clear cache?');

    //dialog returns true..
    if (dialog) {
        MyApp.admin.dashboard.doClearCache();
    }

},

But I have no idea to do this the "right" way.. the dialog can't return an value or?


Solution

  • jQuery ui does not provide a nice way to change the dialog button events.

    I would use a pubsub pattern, tiny pubsub plugin from Cowboyba here or phiggins effort here. It is cleaner than trying to use the jquery ui getters and setters to try to change the buttons and their click events and if you making a large app will help you in lots of other places.

    You can publish the event for the clicking of the ok button and then subscribe and unsubscribe other handlers to listen to the event.

    Quick Demo here to show functionality.