Ohm-Management - Projektarbeit B-ME
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

fromEvent.js 2.4KB

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