ECMAscript6类在事件中的范围

时间:2015-08-26 13:11:08

标签: javascript ecmascript-6

如何将类方法绑定到click-event?

在此示例中,上下文是按钮。我也尝试过箭头符号,没有任何成功。



"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
&#13;
<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>
&#13;
&#13;
&#13;

此致 ħ

1 个答案:

答案 0 :(得分: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