0c52458106ae5f875a582fbbe099cb86b57a0438
[dotfiles/.git] / fromEvent.js
1 /** PURE_IMPORTS_START _Observable,_util_isArray,_util_isFunction,_operators_map PURE_IMPORTS_END */
2 import { Observable } from '../Observable';
3 import { isArray } from '../util/isArray';
4 import { isFunction } from '../util/isFunction';
5 import { map } from '../operators/map';
6 var toString = /*@__PURE__*/ (function () { return Object.prototype.toString; })();
7 export function fromEvent(target, eventName, options, resultSelector) {
8     if (isFunction(options)) {
9         resultSelector = options;
10         options = undefined;
11     }
12     if (resultSelector) {
13         return fromEvent(target, eventName, options).pipe(map(function (args) { return isArray(args) ? resultSelector.apply(void 0, args) : resultSelector(args); }));
14     }
15     return new Observable(function (subscriber) {
16         function handler(e) {
17             if (arguments.length > 1) {
18                 subscriber.next(Array.prototype.slice.call(arguments));
19             }
20             else {
21                 subscriber.next(e);
22             }
23         }
24         setupSubscription(target, eventName, handler, subscriber, options);
25     });
26 }
27 function setupSubscription(sourceObj, eventName, handler, subscriber, options) {
28     var unsubscribe;
29     if (isEventTarget(sourceObj)) {
30         var source_1 = sourceObj;
31         sourceObj.addEventListener(eventName, handler, options);
32         unsubscribe = function () { return source_1.removeEventListener(eventName, handler, options); };
33     }
34     else if (isJQueryStyleEventEmitter(sourceObj)) {
35         var source_2 = sourceObj;
36         sourceObj.on(eventName, handler);
37         unsubscribe = function () { return source_2.off(eventName, handler); };
38     }
39     else if (isNodeStyleEventEmitter(sourceObj)) {
40         var source_3 = sourceObj;
41         sourceObj.addListener(eventName, handler);
42         unsubscribe = function () { return source_3.removeListener(eventName, handler); };
43     }
44     else if (sourceObj && sourceObj.length) {
45         for (var i = 0, len = sourceObj.length; i < len; i++) {
46             setupSubscription(sourceObj[i], eventName, handler, subscriber, options);
47         }
48     }
49     else {
50         throw new TypeError('Invalid event target');
51     }
52     subscriber.add(unsubscribe);
53 }
54 function isNodeStyleEventEmitter(sourceObj) {
55     return sourceObj && typeof sourceObj.addListener === 'function' && typeof sourceObj.removeListener === 'function';
56 }
57 function isJQueryStyleEventEmitter(sourceObj) {
58     return sourceObj && typeof sourceObj.on === 'function' && typeof sourceObj.off === 'function';
59 }
60 function isEventTarget(sourceObj) {
61     return sourceObj && typeof sourceObj.addEventListener === 'function' && typeof sourceObj.removeEventListener === 'function';
62 }
63 //# sourceMappingURL=fromEvent.js.map