Search code examples
jqueryjquery-dialog

Adding OO to jQuery.dialog()


I am developing a web page which contains many jQuery dialogs.

While my code works in principal, I noticed it soon got "dirty", and I feel a strong urge to clean up the code and make it more OO-like.

The main issues with my code are:

  • no dialog-specific state (i.e. set of variables)
  • no dialog-local event handlers
  • dialog-specific functions are global

Which approaches and solutions exist to make jQuery dialog more OO-like, as in Delphi and WinForms?


Solution

  • Maybe the following can help you:

    • no dialog-specific state (i.e. set of variables)

    You can use data() to associate state with the augmented element, as with any element:

    $("#yourDialog").dialog({
        // your options...
    }).data("yourData", {
        some: "state",
        associatedWith: "thisElement"
    });
    

    • no dialog-local event handlers

    What you mean by dialog-local is not clear, but dialog widgets do emit events, and you can of course bind different handlers to events triggered on the inner elements of different dialog widgets.


    • dialog-specific functions are global

    They're not actually global (they're part of the $.fn namespace), but I understand having to call dialog() on the augmented element every time can be seen as unnecessarily heavy.

    That syntax, however, is only a bridge, a way to access the widget's methods more suited to jQuery's idioms. You can obtain a reference to the widget itself using, again, data(), then invoke its methods directly. For instance:

    $("#yourDialog").dialog("open");
    $("#yourDialog").dialog("close");
    

    Is equivalent to:

    var dialogWidget = $("#yourDialog").data("dialog");
    dialogWidget.open();
    dialogWidget.close();
    

    Update: From jQuery UI 1.9 onwards, the data() key becomes the widget's fully qualified name, with dots replaced by dashes. Therefore, the code above becomes:

    var dialogWidget = $("#yourDialog").data("ui-dialog");
    dialogWidget.open();
    dialogWidget.close();
    

    Using the unqualified name is still supported in 1.9 but is deprecated, and support will be dropped in 1.10.