roapp
roapp

Reputation: 742

JS remove event listener from class instances

I'm trying to remove an event listener from my class instance. I would like to create multiple instances from the 'Person' class. Each instance needs to have a listener that will listen to a button press (Speak). I can't figure out how to remove the instances that was previously added. See my code below for more information.

class Person {

    constructor(name) {

        this.name = name; 
        this.createEventListeners();
    }

    createEventListeners() {

        this.speakButton = document.getElementById('speak');
        this.speakButton.addEventListener('click', this.speak.bind(this));
    }

    speak() {
        console.log(this.name + " says hi!")
    }

    destroy() {

        this.speakButton.removeEventListener('click', this.speak);
    }
}


const person1 = new Person('Sylvester');
const person2 = new Person('Arnold');
person2.destroy();

https://jsfiddle.net/av56q7mo/3/

Upvotes: 2

Views: 1209

Answers (1)

Saadi Toumi Fouad
Saadi Toumi Fouad

Reputation: 2829

Ok so why are declaring that button DOM element each time, and you can use arrow functions to keep the value of this so I have changed your code like this:

var speakButton = document.getElementById('speak');
class Person {
  constructor(name) {
    this.name = name; 
    this.createEventListeners();
  }
    
  createEventListeners = _=>       
    speakButton.addEventListener('click', this.speak);
    
  speak = _=>
    console.log(this.name + " says hi!");
    
  destroy = _=>
    speakButton.removeEventListener("click", this.speak);
}

const person1 = new Person('Sylvester');
const person2 = new Person('Arnold');
person2.destroy();
<button id="speak">Speak</button>

Upvotes: 2

Related Questions