What is event-target-polyfill?
The event-target-polyfill npm package provides a polyfill for the EventTarget interface, which is a standard interface implemented by objects that can receive events and may have listeners for them. This is particularly useful for environments that do not natively support EventTarget, such as older browsers or certain JavaScript environments.
What are event-target-polyfill's main functionalities?
Basic EventTarget Implementation
This code demonstrates the basic usage of the EventTarget polyfill. It shows how to create an EventTarget instance, add an event listener, dispatch an event, and remove the event listener.
const { EventTarget, Event } = require('event-target-polyfill');
const target = new EventTarget();
const listener = (event) => {
console.log('Event received:', event.type);
};
target.addEventListener('test', listener);
target.dispatchEvent(new Event('test'));
target.removeEventListener('test', listener);
Custom Event Handling
This example shows how to create and dispatch a custom event with additional data using the EventTarget polyfill. It demonstrates extending the Event class to include custom properties.
const { EventTarget, Event } = require('event-target-polyfill');
class MyCustomEvent extends Event {
constructor(type, customData) {
super(type);
this.customData = customData;
}
}
const target = new EventTarget();
target.addEventListener('custom', (event) => {
console.log('Custom event received with data:', event.customData);
});
target.dispatchEvent(new MyCustomEvent('custom', { key: 'value' }));
Other packages similar to event-target-polyfill
eventemitter3
EventEmitter3 is a high-performance event emitter for Node.js and the browser. It provides a similar event handling mechanism but does not follow the EventTarget interface. Instead, it uses its own API for adding, removing, and emitting events.
mitt
Mitt is a tiny functional event emitter. It provides a simple and minimalistic API for event handling, similar to EventTarget but with a smaller footprint and fewer features. It is ideal for lightweight applications where a full EventTarget implementation is not necessary.
event-target-polyfill
A polyfill for EventTarget
(and Event
), meant to run in older version of node or possibly IE 11, that has the most accurate set of characteristics of EventTarget
that can be provided.
If you find this implementation can be improved, please submit a PR and ping me on Twitter via DM.
NOTE: If you are using Node 14 and higher, EventTarget is available directly via experimental features
MDN: EventTarget
Usage
import 'event-target-polyfill';
const et = new EventTarget();
et.addEventListener('test', () => console.log('hit!'));
et.dispatchEvent(new Event('test'));
Development
This library has no dependencies. Even development dependencies. To test just run npm test
. It runs a script, and if it finishes without error, the tests pass.