jQuery UI Helpers / Events

The HTML helpers do their work on the server and generate HTML elements with data-* attrbutes. The library also contains a small initialization JavaScript file which runs on the client after the document is loaded and uses the data-* attributes to create all the jQuery UI widgets. These widgets are JavaScript objects and run on the client. They do their job without any further configuration, but sometimes you would want to alter their default behaviour or connect them with other parts of your client side code. This is where events come to play.

The jQuery UI widgets expose many events. The fluent configuration API in jQuery UI Helpers supports registering event handlers to all events. All the event registration methods start with 'On' (e.g. OnClose), and take a single string parameter. This parameter must ba a name of a JavaScript function. You may implement these JavaScript funtions in your views or in separate .js files, just be sure they are available when the document is loaded.

If you do not want to pollute the global object with your event handler functions, you do not have to until your functions are accessible somehow and you use the proper names in the event registration methods.

Depending on the widget and event type the event handler functions receive different arguments. Consult the jQuery UI documentation about the details.

Here is an example JavaScript which creates two functions. They will be used to log the close and select events of a datepicker.

var demoEvents = {};
demoEvents.onSelect = function (dateText) {
    $('#eventLog').prepend('<p>Selected ' + dateText + '</p>');
}

demoEvents.onClose = function () {
    $('#eventLog').prepend('<p>Closed.</p>');
}

This is the view which creates the datepicker. Notice how the event handler names are specified.

<div>
<label for="date">Select a date: </label>
@Html.JQueryUI().Datepicker("date").OnClose("demoEvents.onClose").OnSelect("demoEvents.onSelect")
</div>
<div id="eventLog">
</div>

The result is this datepicker. Open it and select a date - the close and select events are logged below it.