Vangde
Vangde

Reputation: 55

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

Upvotes: 0

Views: 635

Answers (1)

javascwipt
javascwipt

Reputation: 1178

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

Upvotes: 1

Related Questions