简体   繁体   中英

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)

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM