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