Search code examples
jqueryjquery-callback

using callback functions in dialogs


I am using the jQuery dialog. I want to be able to use the script for a single the dialog for more than one use. To do so, I am thinking of assigning some callback function which can be called in the dialog. Is this an appropriate way to do so? What do I need to do to make the below code alert "hi" when the dialog button is clicked? Thank you

function somefunction() {alert('hi');}

$("#clickme").click(function(){$("#dialog").data('callback',somefunction).dialog("open");});

$("#dialog").dialog({
    buttons: [
    {
        text    : 'Click',
        click   : function() {
            //If $(this).data('callback') is defined, then execute the function 
        }
    }]
});

Solution

  • There are several different ways to do it (all shown in the documenation).

    Here's one way (the simplest in my opinion):

    $("#dialog").dialog({
        buttons: {
           "Click": function() {
                alert("Hi");
                // execute callback if it is defined
                if (callback) callback();
            }
        }
    });