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
精彩评论