将事件侦听器附加到 class 方法

Attach event listener to a class method

我正在尝试通过 class 方法将事件侦听器添加到元素。 你能告诉我我缺少什么并且它不起作用吗?

class PumpBasic
{
    constructor(_name)
    {
        this.name = _name;
    }

    Foo() 
    {
        this.element = document.getElementById(this.name + "AutoManualSwitch");
        this.element.addEventListener('click', myFunction, false);
    }

    myFunction()
    {
        console.log("clicked");
    }

}

pump1 =new PumpBasic("pump1");

<input  id="pump1AutoManualSwitch" data-on="Manual" data-off="Auto" data-onstyle="primary"  type="checkbox" data-toggle="toggle" data-width="75" data-height="30">

如果您要将 myFunction 方法作为回调函数传递给 addEventListener,您需要使用它来引用它。

您还需要绑定它才能正常工作。如果您不绑定它,全局事件对象会在调用时重新定义它。

这应该有效:

class PumpBasic
{
    constructor(_name)
    {
        this.name = _name;
        this.myFunction = this.myFunction.bind(this)
    }

    Foo() 
    {
        this.element = document.getElementById(this.name + "AutoManualSwitch");
        this.element.addEventListener('click', this.myFunction, false);
    }

    myFunction()
    {
        console.log("clicked");
    }

}

const pump1 = new PumpBasic("pump1");
pump1.Foo()