UNPKG

js-draw

Version:

Draw pictures using a pen, touchscreen, or mouse! JS-draw is a drawing library for JavaScript and TypeScript.

55 lines (54 loc) 1.99 kB
// Code shared with Joplin (from when it was MIT licensed) // (js-draw was originally intended to be part of Joplin). /** * Handles notifying listeners of events. * * `EventKeyType` is used to distinguish events (e.g. a `ClickEvent` vs a `TouchEvent`) * while `EventMessageType` is the type of the data sent with an event (can be `void`). * * @example * ``` * const dispatcher = new EventDispatcher<'event1'|'event2'|'event3', void>(); * dispatcher.on('event1', () => { * console.log('Event 1 triggered.'); * }); * dispatcher.dispatch('event1'); * ``` * */ export default class EventDispatcher { constructor() { this.listeners = {}; } dispatch(eventName, event) { const listenerList = this.listeners[eventName]; if (listenerList) { for (let i = 0; i < listenerList.length; i++) { listenerList[i](event); } } } on(eventName, callback) { if (!this.listeners[eventName]) this.listeners[eventName] = []; this.listeners[eventName].push(callback); return { // Retuns false if the listener has already been removed, true otherwise. remove: () => { const originalListeners = this.listeners[eventName]; this.off(eventName, callback); return originalListeners.length !== this.listeners[eventName].length; }, }; } /** Removes an event listener. This is equivalent to calling `.remove()` on the object returned by `.on`. */ off(eventName, callback) { const listeners = this.listeners[eventName]; if (!listeners) return; // Replace the current list of listeners with a new, shortened list. // This allows any iterators over this.listeners to continue iterating // without skipping elements. this.listeners[eventName] = listeners.filter((otherCallback) => otherCallback !== callback); } }