将事件监听器附加到一个类方法上

问题描述 投票:0回答:1

我试图通过一个类方法将事件监听器添加到一个元素中,你能告诉我我缺少了什么,它没有工作吗?

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">
javascript class methods mouseevent
1个回答
1
投票

如果你要通过 myFunction 方法来添加EventListener作为一个回调函数,你需要使用这个方法来引用它。

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

这应该可以工作。

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()
© www.soinside.com 2019 - 2024. All rights reserved.