开发者

JQuery event handler scope

开发者 https://www.devze.com 2023-04-04 11:03 出处:网络
Say I have this (jqueryUI plugin): $.widget(\'ui.someplugin\', { _create: function() { return $(thi开发者_StackOverflow中文版s.element).click(this._onClick);

Say I have this (jqueryUI plugin):

  $.widget('ui.someplugin', {
    _create: function() {
      return $(thi开发者_StackOverflow中文版s.element).click(this._onClick);
    },
    _onClick: function(e) {
      return this._someFunc();
    },
    _someFunc: function() {
      return console.log('someFunc');
    }
  });

It doesn't work - _onClick receives the DOM element as its scope. I could have the handler reference the plugin again with $(e.target).data('someplugin'), but thats then useless if I want to subscribe to other DOM element events. How do I rejig it so that it does what I want?


Use $.proxy(func, context);, where func will get called with the scope of context.

return $(this.element).click($.proxy(this._onClick, this));

See also: Controlling the value of 'this' in a jQuery event

0

精彩评论

暂无评论...
验证码 换一张
取 消