fromEvent.js 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. import { innerFrom } from '../observable/innerFrom';
  2. import { Observable } from '../Observable';
  3. import { mergeMap } from '../operators/mergeMap';
  4. import { isArrayLike } from '../util/isArrayLike';
  5. import { isFunction } from '../util/isFunction';
  6. import { mapOneOrManyArgs } from '../util/mapOneOrManyArgs';
  7. const nodeEventEmitterMethods = ['addListener', 'removeListener'];
  8. const eventTargetMethods = ['addEventListener', 'removeEventListener'];
  9. const jqueryMethods = ['on', 'off'];
  10. export function fromEvent(target, eventName, options, resultSelector) {
  11. if (isFunction(options)) {
  12. resultSelector = options;
  13. options = undefined;
  14. }
  15. if (resultSelector) {
  16. return fromEvent(target, eventName, options).pipe(mapOneOrManyArgs(resultSelector));
  17. }
  18. const [add, remove] = isEventTarget(target)
  19. ? eventTargetMethods.map((methodName) => (handler) => target[methodName](eventName, handler, options))
  20. :
  21. isNodeStyleEventEmitter(target)
  22. ? nodeEventEmitterMethods.map(toCommonHandlerRegistry(target, eventName))
  23. : isJQueryStyleEventEmitter(target)
  24. ? jqueryMethods.map(toCommonHandlerRegistry(target, eventName))
  25. : [];
  26. if (!add) {
  27. if (isArrayLike(target)) {
  28. return mergeMap((subTarget) => fromEvent(subTarget, eventName, options))(innerFrom(target));
  29. }
  30. }
  31. if (!add) {
  32. throw new TypeError('Invalid event target');
  33. }
  34. return new Observable((subscriber) => {
  35. const handler = (...args) => subscriber.next(1 < args.length ? args : args[0]);
  36. add(handler);
  37. return () => remove(handler);
  38. });
  39. }
  40. function toCommonHandlerRegistry(target, eventName) {
  41. return (methodName) => (handler) => target[methodName](eventName, handler);
  42. }
  43. function isNodeStyleEventEmitter(target) {
  44. return isFunction(target.addListener) && isFunction(target.removeListener);
  45. }
  46. function isJQueryStyleEventEmitter(target) {
  47. return isFunction(target.on) && isFunction(target.off);
  48. }
  49. function isEventTarget(target) {
  50. return isFunction(target.addEventListener) && isFunction(target.removeEventListener);
  51. }
  52. //# sourceMappingURL=fromEvent.js.map