我想從類內調用一個類函數,我之前將其附加到駐留在類中的按鈕對象(下面的代碼工作,但callMyClassFunction中的作用域在按鈕上並且我希望它是旋轉木馬):作用域在JavaScript中引用事件處理程序
//Examplecode 1
Carousel.prototype.addEventListeners = function(){
this.button.on('click', this.callMyClassFunction);
}
Carousel.prototype.callMyClassFunction = function(){
console.log(this);
}
如果我綁定的功能一樣,它的工作原理(這個範圍是類的實例):
//Examplecode 2
Carousel.prototype.addEventListeners = function(){
this.button.on('click', function(){
this.callMyClassFunction()
}).bind(this);
}
但我寧願要添加click-eventlistener和引用(就像例子代碼1一樣),因爲我想要c所有removeListener在另一個功能:
//Examplecode 3
Carousel.prototype.removeEventListeners = function(condition){
if(condition){
this.button.removeListener('click', this.callMyClassFunction);
}
}
任何幫助非常感謝!
非常感謝,這工作正常。但對於傾聽者,我更喜歡Bergi的方法。 – doemsche 2014-10-07 12:49:19
是的,這也起作用,前提是你永遠不需要這種方法解除綁定(你經常不需要)。 – 2014-10-07 12:52:28