如何处理jQuery UI小部件中的事件

Aru*_*hny 9 javascript jquery jquery-ui

我正在尝试按照此处给出的模型编写一个jQuery小部件.这是小部件的快照:

(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);
Run Code Online (Sandbox Code Playgroud)

这里的问题在于_titleClick方法内部的"this"范围,在方法内部指向title元素.但我需要它指向widget元素.

我认为这样做的一种方法是使用类似的包装类

var that = this;
this.elTitle.click(function() {
    that._titleClick.apply(that, arguments);
});
Run Code Online (Sandbox Code Playgroud)

这是解决此问题的最佳方法,还是有任何解决此问题的一般模式?

Jen*_*ann 21

使用该this._on()方法绑定处理程序.此方法由jQuery UI小部件工厂提供,并将确保在处理程序函数内this始终引用小部件实例.

_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.
},
Run Code Online (Sandbox Code Playgroud)


小智 5

你应该看看jQuery.proxy()http://api.jquery.com/jQuery.proxy/

el.bind('evenname', $.proxy(function () {
   this.isMyScope.doSomething();
}, scope));
Run Code Online (Sandbox Code Playgroud)


Aru*_*hny 3

我自己写了一个方法来解决这个问题

_wrapCallback : function(callback) {
    var scope = this;
    return function(eventObject) {
        callback.call(scope, this, eventObject);
    };
}
Run Code Online (Sandbox Code Playgroud)