2015-08-26 16 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