我有一个对象 ChatHandler
,它拥有一个 div,并且它的 div 包含一些其他 dom 元素。然后,我将事件处理程序绑定(bind)到其中包含的 DOM 元素的某个子集,如下所示:
$(this.element).find('.render-box').unbind('click').click(this.handleBoxClick);
我指定了一些函数来处理这些点击。
ChatHandler.prototype.handleBoxClick = function(event) {
// 'this' refers to a DOM object.
var partner = $(this).attr('partnerid');
// But now I want to be able to access a public attribute of this object.
this.myAttribute = partner;
}
然后我如何访问 ChatHandler 对象的公共(public)成员/函数?我假设我无法更改执行上下文,但我肯定缺少某种方法来执行此操作。
最佳答案
使用$.proxy
绑定(bind)this
值。
$(this.element).find('.render-box')
.unbind('click')
.click($.proxy(this, "handleBoxClick"));
或者,如果您需要在处理程序中保留默认 this
值,则可以将对象作为事件数据传递。
$(this.element).find('.render-box')
.unbind('click')
.click(this, this.handleBoxClick);
然后通过处理程序中的 event.data
访问它。
ChatHandler.prototype.handleBoxClick = function(event) {
var partner = $(this).attr('partnerid');
event.data.myAttribute = partner;
}
关于Javascript 'this' 上下文与 jQuery,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16380858/