Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Removing Event Listeners within ES6 Classes

Let’s say I have a button within my class in the function doStuff(). Can I delete this event listener within the Pet Class? Or do I need to globally do it.

Something like this:

I know I need to call myButton.removeEventListener(‘click’, myPet.sayHello)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

class Pet {
  constructor () {
    this.age = 10;
    this.name = "Boris";
  }

  sayHello () {
    console.log('Bark Bark!')
  }

  doStuff() {
    const myButton = document.createElement('button');
    myButton.innerText = "Click me!";
    document.body.appendChild(myButton)
    myButton.addEventListener('click', this.sayHello)
  }
}

const myPet = new Pet();
myPet.doStuff();

>Solution :

Yes, you can remove the event listener inside the class.

class Pet {
  constructor () {
    this.age = 10;
    this.name = "Boris";
  }

  sayHello () {
    alert('Bark Bark!');
  }

  doStuff() {
    const myButton = document.createElement('button');
    document.body.appendChild(myButton);
    const listener = () => {
      this.sayHello();
      myButton.removeEventListener('click', listener);
    };
    myButton.addEventListener('click', listener);
  }
}

const myPet = new Pet();
myPet.doStuff();
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading