removeEventListener does not work within a class

2

I have the following JavaScript code, where the removeEventListener method does not work for me within a class:

class Removerevento {
  constructor() {
    this._btndos = document.getElementById('btnDos');
    this._btntres = document.getElementById('btnTres');
  }

  btnUno() {
    console.log("Boton uno");
    this._btndos.addEventListener('click', this.btnDos, false);
    this._btntres.addEventListener('click', this.btnTres, false);
  }

  btnDos() {
    console.log('Boton dos');
  }

  btnTres() {
    console.log('Boton tres');
    this._btndos.removeEventListener('click', this.btnDos, false);
  }
}

let rm = new Removerevento;
document.getElementById('btnUno')
  .addEventListener('click', function() {
    rm.btnUno();
  }, false);
<button id="btnUno">Uno</button>
<button id="btnDos">Dos</button>
<button id="btnTres">Tres</button>

The steps to reproduce the problem are: press button One and then press button 3. Then it says that you can not use removeEventListener in undefined .

Why does that happen? How can I solve it?

    
asked by vtrmq 05.11.2017 в 02:25
source

1 answer

0

The problem is that the value of this is not what you think it is. When a function associated with an event is called, this will be the element that launched the event (even if the function called is within a class).

For this to be the object and not the element that throws the event, you must use bind . Adding .bind(this) would be forcing the value of this to the moment in which the event is associated and not in the one that is triggered.

Here you can see it working:

class Removerevento {
  constructor() {
    this._btndos = document.getElementById('btnDos');
    this._btntres = document.getElementById('btnTres');
  }

  btnUno() {
    console.log("Boton uno");
    this._btndos.addEventListener('click', this.btnDos, false);
    this._btntres.addEventListener('click', this.btnTres.bind(this), false);
  }

  btnDos() {
    console.log('Boton dos');
  }

  btnTres() {
    console.log('Boton tres');
    this._btndos.removeEventListener('click', this.btnDos, false);
  }
}

let rm = new Removerevento;
document.getElementById('btnUno')
  .addEventListener('click', function() {
    rm.btnUno();
  }, false);
<button id="btnUno">Uno</button>
<button id="btnDos">Dos</button>
<button id="btnTres">Tres</button>
    
answered by 05.11.2017 в 03:20