George R
George R

Reputation: 3860

JQuery event handler scope

Say I have this (jqueryUI plugin):

  $.widget('ui.someplugin', {
    _create: function() {
      return $(this.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?

Upvotes: 1

Views: 5317

Answers (1)

bbg
bbg

Reputation: 3072

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

Upvotes: 7

Related Questions