Suppose we want to put an event handler, and remove it right there:

let button = document.getElementById('button'); function func() { console.log('Π‘Ρ€Π°Π±ΠΎΡ‚Π°Π»ΠΎ'); } button.addEventListener('click', func); button.removeEventListener('click', func); 
 <button id="button">Кликни</button> 

Great, func didn't work.

But what happens if the handler has functions with this?

 let button = document.getElementById('button'); let objWithFunc = { func() { console.log('Π‘Ρ€Π°Π±ΠΎΡ‚Π°Π»ΠΎ'); }, start() { function auxiliaryFunc() { this.func(); } // Π’ΠΎΡΠΏΠΎΠ»ΡŒΠ·ΡƒΠ΅ΠΌΡΡ .bind(this) ΠΈΠ½Π°Ρ‡Π΅ Π±ΡƒΠ΄Π΅Ρ‚ ошибка button.addEventListener('click', auxiliaryFunc.bind(this)); // Ни ΠΎΠ΄ΠΈΠ½ ΠΈΠ· ΡΠ»Π΅Π΄ΡƒΡŽΡ‰ΠΈΡ… ΠΌΠ΅Ρ‚ΠΎΠ΄ΠΎΠ² Π½Π΅ снимСт ΠΎΠ±Ρ€Π°Π±ΠΎΡ‚Ρ‡ΠΈΠΊ button.removeEventListener('click', auxiliaryFunc); button.removeEventListener('click', auxiliaryFunc.bind(this)); } } objWithFunc.start(); 
 <button id="button">Кликни</button> 

How to remove the handler in this case?

    2 answers 2

    .bind() creates a new function. It is her, and not created a new, you need to pass to removeEventListener

      const listener = auxiliaryFunc.bind(this) button.addEventListener('click', listener); button.removeEventListener('click', listener); 
    • one
      "It is her, and not created a new one" - a little difficult to formulate, rather - in addEventListener and removeEventListener you need to pass a link to the same function. - MedvedevDev

    A little off topic, but you can do without .bind(this) in the realities of es6.

     const button = document.getElementById('button'); const objWithFunc = { func() { console.log('Π‘Ρ€Π°Π±ΠΎΡ‚Π°Π»ΠΎ'); }, start() { const auxiliaryFunc = () => { this.func(); } button.addEventListener('click', auxiliaryFunc); button.removeEventListener('click', auxiliaryFunc); } } objWithFunc.start(); 
     <button id="button">Кликни</button>