rxjs-zone-less
Version:
A set of wrappers for RxJS to avoid unnecessary change detection and zone interference in Angular.
80 lines (79 loc) • 2.86 kB
JavaScript
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { getZoneUnPatchedApi } from '../internals/zone-less';
// @ts-ignore
function isFunction(fn) {
return typeof fn === 'function';
}
var isArray = Array.isArray;
export function fromEvent(target, eventName, options, resultSelector) {
if (isFunction(options)) {
// DEPRECATED PATH
// @ts-ignore
resultSelector = options;
options = undefined;
}
if (isFunction(resultSelector)) {
// DEPRECATED PATH
return fromEvent(target, eventName, options).pipe(map(function (args) {
return isArray(args) ? resultSelector.apply(void 0, args) : resultSelector(args);
}));
}
return new Observable(function (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) {
var unsubscribe;
if (isEventTarget(sourceObj)) {
var source_1 = sourceObj;
getZoneUnPatchedApi(sourceObj, 'addEventListener').call(sourceObj, eventName, handler, options);
unsubscribe = function () {
return getZoneUnPatchedApi(source_1, 'removeEventListener').call(source_1, eventName, handler, options);
};
}
else if (isJQueryStyleEventEmitter(sourceObj)) {
var source_2 = sourceObj;
sourceObj.on(eventName, handler);
unsubscribe = function () { return source_2.off(eventName, handler); };
}
else if (isNodeStyleEventEmitter(sourceObj)) {
var source_3 = sourceObj;
sourceObj.addListener(eventName, handler);
unsubscribe = function () {
return source_3.removeListener(eventName, handler);
};
}
else if (sourceObj && sourceObj.length) {
for (var 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');
}