A tiny, dependency-free event system for plain objects. Works in browsers, React Native (Hermes and JSC) and Node, and ships ESM, CommonJS and TypeScript types.
Unlike the DOM's EventTarget, each listener gets its own copy of the event,
with the event's detail spread onto it, so you read event.value rather than
event.detail.value.
npm install --save @atomic-reactor/event-handleimport { EventTarget, Event } from '@atomic-reactor/event-handle';
class DatePicker extends EventTarget {
setDate(value: Date) {
this.dispatchEvent(new Event('date-changed', { value }));
}
}
const picker = new DatePicker();
picker.addEventListener('date-changed', (event) => {
console.log(event.type, event.value); // "date-changed", Date
});
picker.setDate(new Date());addEventListener and removeEventListener return the target, so calls can
be chained.
Calling event.stopPropagation() in a listener stops the remaining listeners
for that dispatch from being called.
picker.addEventListener('date-changed', (event) => {
if (!event.value) event.stopPropagation();
});| Property | Description |
|---|---|
type |
The event type |
target |
The EventTarget that dispatched it |
timeStamp |
Date.now() when the Event was created |
currentTarget |
The name of the function that called dispatchEvent, for debugging (mangled in minified builds; "anonymous" when unavailable) |
stopPropagation() |
Stops later listeners in this dispatch |
isPropagationStopped |
Whether propagation has been stopped |
| ...detail | Every key of the detail object |
Detail keys that clash with the fields above are ignored.
EventTarget and Event share names with browser (and newer React Native)
globals. Importing them shadows the globals in that module only; if you need
both, rename on import:
import {
EventTarget as Emitter,
Event as AppEvent,
} from '@atomic-reactor/event-handle';The library uses only ES2019 built-ins (Map, Set, Object.keys,
Date.now, Error().stack) and is compiled to ES2019, so it needs no
polyfills in any current browser, React Native 0.60+ or Node 12+.
MIT