UNPKG

@reactivex/ix-es2015-cjs

Version:

The Interactive Extensions for JavaScript

49 lines (47 loc) 2.37 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.fromEvent = void 0; const fromeventpattern_js_1 = require("./fromeventpattern.js"); const isiterable_js_1 = require("../util/isiterable.js"); function isMessagePortEventEmitter(obj) { return !!obj && (0, isiterable_js_1.isFunction)(obj.on) && (0, isiterable_js_1.isFunction)(obj.off); } function isNodeEventEmitter(obj) { return !!obj && (0, isiterable_js_1.isFunction)(obj.addListener) && (0, isiterable_js_1.isFunction)(obj.removeListener); } function isEventTarget(obj) { return !!obj && (0, isiterable_js_1.isFunction)(obj.addEventListener) && (0, isiterable_js_1.isFunction)(obj.removeEventListener); } /** * Converts an event emitter event into an async-iterable stream. * * @template TSource The type of elements in the emitter stream. * @param {EventedTarget} obj The object that emits the events to turn into an async-iterable. * @param {string} type The name of the event to listen for creation of the async-iterable. * @param {EventListenerOptions} [options] The options for listening to the events such as capture, passive and once. * @param {(...args: any[]) => TSource} [resultSelector] The result selector for the event. * @returns {AsyncIterableX<TSource>} An async-iterable sequence created from the events emitted from the evented target. */ function fromEvent(obj, type, options, resultSelector) { if ((0, isiterable_js_1.isFunction)(options)) { resultSelector = options; options = undefined; } if (isEventTarget(obj)) { const target = obj; return (0, fromeventpattern_js_1.fromEventPattern)((h) => target.addEventListener(type, h, options), (h) => target.removeEventListener(type, h, options), resultSelector); } else if (isMessagePortEventEmitter(obj)) { const target = obj; return (0, fromeventpattern_js_1.fromEventPattern)((h) => target.on(type, h), (h) => target.off(type, h), resultSelector); } else if (isNodeEventEmitter(obj)) { const target = obj; return (0, fromeventpattern_js_1.fromEventPattern)((h) => target.addListener(type, h), (h) => target.removeListener(type, h), resultSelector); } else { throw new TypeError('Unsupported event target'); } } exports.fromEvent = fromEvent; //# sourceMappingURL=fromevent.js.map