ECMAscript6类在事件中的作用域

ECMAscript6 class scopes in events

本文关键字:作用域 事件 ECMAscript6      更新时间:2023-09-26

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

在这个示例中,上下文是button。我也尝试过箭头符号,但没有成功。

"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

在构造函数中,您需要将clickEvents绑定到this

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

因为它看起来像你想要删除你的even监听器之后你应该实际存储一个引用到那个绑定函数因为那是你需要在你的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');
    }
}

您可以轻松地在这里使用箭头符号,只需在构造函数中创建特定于实例的方法:

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

或者,您可以使用@Jonathan充实的bind,或任何标准方法。