2015-08-26 15 views
0

如何將類方法綁定到click事件中?事件中的ECMAscript6類作用域

在此示例中,上下文是按鈕。我也嘗試了箭頭符號,沒有任何成功。

"use strict"; 
 
class Foo { 
 
    constructor() { 
 
     $('html').prepend('<button id="btn">Click me!</button>'); 
 
     $('#btn').bind('click', this.clickEvents); 
 
    } 
 

 
    clickEvents(e) { 
 
     //Have to use as a function, otherwise unbind won't work 
 
     e.stopPropagation(); 
 
     // How to point to sayBoo-function? 
 
     debugger; 
 
     this.sayBoo(); //Points to <button id="btn"... 
 
    } 
 
    
 
    doUnBindings(){ 
 
     $('#btn').unbind('click', this.clickEvents); 
 
    } 
 

 
    sayBoo() { 
 
     alert('boo'); 
 
    } 
 
} 
 

 
const f = new Foo(); // eslint-disable-line no-unused-vars, prefer-const
<script src="https://cdnjs.cloudflare.com/ajax/libs/es6-shim/0.33.1/es6-shim.min.js"></script> 
 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

此致 ^ h

+1

你是怎麼使用箭頭的? – Bergi

回答

2

在你的構造函數,你需要clickEvents結合this

$('#btn').bind('click', this.clickEvents.bind(this)); 

而且因爲它看起來像你想稍後刪除您甚至監聽器你應該實際存儲對該綁定函數的引用e這就是你需要在你的doUnBindings方法中使用的東西。

所以,最後你可能想要的東西,看起來像這樣

"use strict"; 
class Foo { 
    constructor() { 
     $('html').prepend('<button id="btn">Click me!</button>'); 
     this.boundClickEvents = this.clickEvents.bind(this); 
     $('#btn').bind('click', this.boundClickEvents); 
    } 

    clickEvents(e) { 
     //Have to use as a function, otherwise unbind won't work 
     e.stopPropagation(); 
     // How to point to sayBoo-function? 
     debugger; 
     this.sayBoo(); //Points to <button id="btn"... 
    } 

    doUnBindings(){ 
     $('#btn').unbind('click', this.boundClickEvents); 
    } 

    sayBoo() { 
     alert('boo'); 
    } 
} 
+0

這很好。我希望ES6能夠爲普通模式帶來更簡單的解決方案。 –

+0

我不會調用函數綁定hacky,但如果您正在尋找一種更習慣的做事方式,您可能需要嘗試通過在箭頭函數中調用this.clickEvents來將Bergi的解決方案與此解決方案相結合。我實際上並不建議這樣做,因爲它僅僅依賴於箭頭函數,無非是已經綁定的東西。它會要求你轉發事件參數。 – Jonathan

2

您可以輕鬆地在這裏使用的箭頭符號,就創建在構造函數實例,具體方法:

class Foo { 
    constructor() { 
     this.clickEvents = (e) => { 
      e.stopPropagation(); 
      this.sayBoo(); 
     }; 
    } 
    doBindings() { 
     $('#btn').bind('click', this.clickEvents); 
    } 
    doUnbindings(){ 
     $('#btn').unbind('click', this.clickEvents); 
    } 
    sayBoo() { … } 
} 

另外,您可以使用bind作爲@Jonathan或任何standard approaches

+0

...沒有意識到我無法在代碼中發佈代碼塊。 – Jonathan

+1

@Jonathan:是的,但那些實驗性很強。我不能推薦他們的用法。 – Bergi