Monday, December 9, 2013

Responding To Dialog Open and Close Events

The jQuery UI dialog widget, just like every other widget, triggers events to reflect changes in state. For example, when a dialog is opened, it enters an "open" state, and the dialogopen event is how this change is communicated to the outside world. This means that any element can listen to these events, including the body element. Listening for dialog events after they've bubbled up the DOM is handy for implementing generic behavior.

For example, let's say that when a dialog is opened, we want to disable other button widgets on the page. But we only need to do this if the dialog isn't a modal dialog. If it is modal, there's an overlay inserted into the page, preventing interactions outside of the dialog from happening.

$( "body" ).on({

    dialogopen: function( e ) {
        if ( !$( e.target ).dialog( "option", "modal" ) ) {
            $( ".buttons :ui-button" ).button( "disable" );
        }
    },
    
    dialogclose: function( e ) {
        $( ".buttons :ui-button" ).button( "enable" );
    }

});

This is different from the common jQuery UI event handlers, where they're passed into the widget constructor. This is good for specific behavior, but when you have something generic that you want to run for all widgets, even new instances that have yet to be created, this approach works well.