Skip to content Skip to sidebar Skip to footer

Jquery Widget Factory Access Options In A Callback Method

I'm trying to create a jQuery control using the widget factory. The idea is that I turn a button into a jQuery button, give it an icon, and register the click event for that button

Solution 1:

After playing with it for a few hours, I finally came across the jQuery Proxy method which is exactly what I was looking for. I changed the code a little bit to look like this:

$.widget("calendarButton", {
    options: {
        textFieldId: ''
    },
    _create: function () {
        this.element.button(
         {
             icons: {
                 primary: "ui-icon-calendar"
             }
         }).on("click", $.proxy(this._clickHandler, this));
    },
    _clickHandler: function () {
        if (this.options.textFieldId != '') {
            $(this.options.textFieldId).datetimepicker('show');
        }
    }
});

Notice that instead of implementing the click callback directly, I'm essentially creating a delegate that points to my private _clickHandler function, which itself runs on the same context as the $.widget() method (since the second argument of $.proxy(this._clickHandler, this) returns $.widget()'s context) hence availablity of the options variable inside the method.

Post a Comment for "Jquery Widget Factory Access Options In A Callback Method"