2014-10-07 32 views
0

我想從類內調用一個類函數,我之前將其附加到駐留在類中的按鈕對象(下面的代碼工作,但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); 
    } 
} 

任何幫助非常感謝!

回答

1

綁定的監聽器只是存儲在您的實例:

functin Carousel(…) { 
    … 
    this.callMyClassFunction = this.callMyClassFunction.bind(this); 
} 
Carousel.prototype.callMyClassFunction = function(){ 
    console.log(this); 
}; 
Carousel.prototype.addEventListeners = function(){ 
    this.button.on('click', this.callMyClassFunction); 
}; 
Carousel.prototype.removeEventListeners = function(…){ 
    … 
    this.button.removeListener('click', this.callMyClassFunction); 
}; 
1

您可以使用bind而更簡單地說:

Carousel.prototype.addEventListeners = function(){ 
    this.button.on('click', this.callMyClassFunction.bind(this)); 
}; 

我不知道你正在使用你的榜樣是什麼bind(你在on函數的返回值調用它),但上述使用Function#bind,這是JavaScript本身的一部分(從ES5開始;對於舊版瀏覽器很容易實現填充/填充)。 Function#bind返回一個新函數,該函數在調用時調用原始函數this設置爲您給bind的第一個參數。因此,在上面,點擊將調用bind返回的函數,這將調用callMyClassFunctionthis設置爲正確的值。

如果以後需要使用removeListener,它需要相同功能被傳遞到它,你必須要記住的功能,像這樣:

Carousel.prototype.addEventListeners = function(){ 
    if (!this.boundCallMyClassFunction) { 
     this.boundCallMyClassFunction = this.callMyClassFunction.bind(this); 
    } 
    this.button.on('click', this.boundCallMyClassFunction); 
}; 

Carousel.prototype.removeEventListeners = function(condition){ 
    if(condition && this.boundCallMyClassFunction){ 
     this.button.removeListener('click', this.boundCallMyClassFunction); 
    } 
}; 

你不能僅僅把它傳遞再次調用bind的結果,因爲這將是一個不同的功能。

但檢查任何真實提供你上面調用onremoveListener功能的文檔,它可以提供一個更簡單的方法來做到這一點(jQuery不會,但它並不像你使用jQuery那裏)。

+0

非常感謝,這工作正常。但對於傾聽者,我更喜歡Bergi的方法。 – doemsche 2014-10-07 12:49:19

+0

是的,這也起作用,前提是你永遠不需要這種方法解除綁定(你經常不需要)。 – 2014-10-07 12:52:28

相關問題