UNPKG

1.48 kBJavaScriptView Raw
1import { fromEventPattern } from './fromeventpattern';
2function isNodeEventEmitter(obj) {
3 return !!obj && typeof obj.addListener === 'function' && typeof obj.removeListener === 'function';
4}
5function isEventTarget(obj) {
6 return (!!obj &&
7 typeof obj.addEventListener === 'function' &&
8 typeof obj.removeEventListener === 'function');
9}
10/**
11 * Converts an event emitter event into an async-iterable stream.
12 *
13 * @export
14 * @template TSource The type of elements in the emitter stream.
15 * @param {EventedTarget} obj The object that emits the events to turn into an async-iterable.
16 * @param {string} type The name of the event to listen for creation of the async-iterable.
17 * @param {EventListenerOptions} [options] The options for listening to the events such as capture, passive and once.
18 * @returns {AsyncIterableX<TSource>} An async-iterable sequence created from the events emitted from the evented target.
19 */
20export function fromEvent(obj, type, options) {
21 if (isEventTarget(obj)) {
22 const target = obj;
23 return fromEventPattern((h) => target.addEventListener(type, h, options), (h) => target.removeEventListener(type, h, options));
24 }
25 else if (isNodeEventEmitter(obj)) {
26 const target = obj;
27 return fromEventPattern((h) => target.addListener(type, h), (h) => target.removeListener(type, h));
28 }
29 else {
30 throw new TypeError('Unsupported event target');
31 }
32}
33
34//# sourceMappingURL=fromevent.mjs.map