JQuery事件处理程序范围

Geo*_*e R 1 jquery jquery-ui

说我有这个(jqueryUI插件):

  $.widget('ui.someplugin', {
    _create: function() {
      return $(this.element).click(this._onClick);
    },
    _onClick: function(e) {
      return this._someFunc();
    },
    _someFunc: function() {
      return console.log('someFunc');
    }
  });
Run Code Online (Sandbox Code Playgroud)

它不起作用 - _onClick接收DOM元素作为其范围.我可以让处理程序再次使用$(e.target).data('someplugin')引用该插件,但如果我想订阅其他DOM元素事件那就没用了.我如何重新调整它以便它能够满足我的需求?

bbg*_*bbg 7

使用$.proxy(func, context);,func将在哪里调用范围context.

return $(this.element).click($.proxy(this._onClick, this));
Run Code Online (Sandbox Code Playgroud)

另请参阅:在jQuery事件中控制"this"的值