<button class='button'>Try events after registering</button>
<p>Placeholder for events triggered</p>
<button onclick="registerHandlers()">Register Handlers</button>
<button onclick="unregisterClick()">Unregister Click</button>
<button onclick="unregisterAll()">Unregister All</button>
class Handler {
  
  #element;
  #eventMap={};

  constructor(element, eventMap) {
    this.#element = element;
    this.register(eventMap);
  }
  
  handleEvent(e) {
    this.#eventMap[e.type](e);
  }
  
  register(eventMap) {
    this.#eventMap = { ...this.#eventMap, ...eventMap };
    Object.keys(this.#eventMap).forEach((event) => {
      this.#element.addEventListener(event, this);
    });
  }
  
  unregister(event) {
    this.#element.removeEventListener(event, this);
  }
  
  unregisterAll() {
    Object.keys(this.#eventMap).forEach((event) => {
      this.#element.removeEventListener(event, this);
    });
  }
}

const element = document.querySelector(".button");

const handler = new Handler(element, {
  click: clickHandler,
  focus: focusHandler,
  random:()=>alert('wow')
});

const p = document.querySelector("p");

function clickHandler(e) {
  p.textContent = `click fired`;
}

function focusHandler() {
  p.textContent = `focus fired`;
}

function blurHandler() {
  p.textContent = `blur fired`;
}

function registerHandlers() {
  handler.register({
    click: () => {
      p.textContent = "click fired by new registered handler";
    },
    blur:blurHandler
  });
}

function unregisterClick() {
  handler.unregister("click");
}

function unregisterAll() {
  handler.unregisterAll();
  p.textContent = "Placeholder for events triggered";
}

External CSS

This Pen doesn't use any external CSS resources.

External JavaScript

This Pen doesn't use any external JavaScript resources.