To switch EventListeners on the button, you would do exactly as you suggested
button.addEventListener("click", test)
button.removeEventListener("click", test)
button.addEventListener("click", test2)
An EventListener is essentially one of two things.
- A function that accepts an event object as an input parameter.
- An object that has a handleEvent function that accepts an event object as an input parameter.
For test2 to be an EventListener, it would just need to be one of those two things.
Option 1: As a function
function test2(event) {
console.log(event)
}
button.addEventListener("click", test2)
Option 2: As an object with a handleEvent function
const test2 = {
"handleEvent": (event) => {
console.log(event)
}
}
button.addEventListener("click", test2)
The documentation to support this can be found here:
https://developer.mozilla.org/en-US/docs/Web/API/EventListener