Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle events in jQuery UI widgets

I'm trying to write a jQuery widget following the model given here. Here is a snapshot of the widget:

(function ($) {
    $.widget("ui.notification", {
        _create: function () {
            if (!this.element.hasClass("ntfn")) {
                this.element.addClass("ntfn");
            }

            this.elTitle = this.element.append("<div class='ntfn-title'>Notifications</div>");

            this.elTitle.click(this._titleClick)
        },
        _titleClick: function () {
            console.log(this);
        }
    });
})(jQuery);

Here the problem is with the scope of "this" inside the _titleClick method, inside the method this points to the title element. But I need it to point to the widget element.

I think one way of doing it will be to use a wrapper class like

var that = this;
this.elTitle.click(function() {
    that._titleClick.apply(that, arguments);
});

Is this the best way to solve this problem or is there any general pattern to solve this issue?

like image 488
Arun P Johny Avatar asked Oct 26 '10 07:10

Arun P Johny


People also ask

What is event and UI in jQuery?

The event object is the original object that was fired, normalized by jQuery. Meanwhile, the ui object contains information added by jQuery UI, depending on which interaction was used. Depending on whether you utilized the properties in either of these objects may be the reason why you passed the exercise.

What is a jQuery UI widget?

a jQuery UI widget is a specialized jQuery plug-in. Using plug-in, we can apply behaviours to the elements. However, plug-ins lack some built-in capabilities, such as a way to associate data with its elements, expose methods, merge options with defaults, and control the plug-in's lifetime.

What is jQuery UI Why is it needed?

jQuery UI is a curated set of user interface interactions, effects, widgets, and themes built on top of the jQuery JavaScript Library. Whether you're building highly interactive web applications or you just need to add a date picker to a form control, jQuery UI is the perfect choice.


1 Answers

Use the this._on() method to bind the handler. This method is provided by the jQuery UI widget factory and will make sure that within the handler function, this always refers to the widget instance.

_create: function () {
    ...
    this._on(this.elTitle, {
        click: "_titleClick" // Note: function name must be passed as a string!
    });
},
_titleClick: function (event) {
    console.log(this);       // 'this' is now the widget instance.
},
like image 117
Jens Bannmann Avatar answered Oct 16 '22 13:10

Jens Bannmann