0

I have a button, which runs a event listener on click. But the event is running on each click. I want to run the event only once.

So I added a second button, which I want to use for removing the event listener. But this doesn't work, the event is running a few times. So when I press the run button 5 times for example, it runs the event 5 times.

I need to remove the event on clicking the remove button, to reset the event listener to 0.

Run event function:

setListenerOnClick() {
    this.window.addEventListener(this.testEvent, event => {
        console.log('Test ' + event);
    });

    this.window.addEventListener(this.test2Event, event => {
        console.log('Test 2 ' + event);
    });
}

Remove event function:

removeListener() {
    this.window.removeEventListener(this.testEvent, event);
    this.window.removeEventListener(this.test2Event, event);
}

Tried to add the function to a new function and replace the event with that function, but that didn't work. Adding the option 'once' is not an option because it's not working on IE11.

I want to run the event on clicking the run button, and clear/remove on clicking the remove button.

Any ideas?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
can
  • 214
  • 2
  • 14

0 Answers0