简体   繁体   中英

Attach event listener to a class method

Im trying to add event listener to an element through a class method. Can you tell me what im missing and its not working?

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">

If you are going to pass the myFunction method to addEventListener as a callback function you need to reference it by using this.

You also need to bind it for it work properly. The global Event object redefines this at calltime if you do not bind it.

This should work:

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM