Implement addEventListener, removeEventListener, dispatchEvent
You are tasked with building an EventTarget class in JavaScript, structured to efficiently handle events. This class is fundamental for registering event listeners, removing these listeners, and dispatching events to the registered listeners. Compare your EventTarget class with the browser’s native EventTarget.
The EventTarget class should encapsulate three primary methods:
Example Usage:
const et = new EventTarget();
et.addEventListener('click', () => console.log('Clicked!'));
et.dispatchEvent('click'); // Output: "Clicked!"
et.removeEventListener('click', () => console.log('Clicked!'));
et.dispatchEvent('click'); // No output, as the listener has been removed.
This EventTarget implementation offers a streamlined and adaptable approach to managing events within event-driven programming paradigms, allowing for the dynamic addition and removal of event handlers and the capability to programmatically initiate events.