observables/fromEvent.js

  1. import { Observable } from '../Observable';
  2. import { makeHot } from '../utilities/makeHot';
  3. /**
  4. * Will create an observable that will listen for an event on a DOM element
  5. *
  6. * Utilizes the [`makeHot`](#makehot) method so that the event does not get reattached on every subscription
  7. *
  8. * @memberof observables
  9. *
  10. *
  11. * @param {string} eventName
  12. * @param {Element} element
  13. * @param {Function} [mapCallback]
  14. * @returns {Observable}
  15. */
  16. export const fromEvent = function (eventName, element, mapCallback = (v) => v) {
  17. return makeHot(new Observable(function ({ next }) {
  18. const listener = function (event) {
  19. next(mapCallback(event));
  20. };
  21. element.addEventListener(eventName, listener, false);
  22. return function () {
  23. element.removeEventListener(eventName, listener, false);
  24. };
  25. }));
  26. };
  27. Observable.fromEvent = fromEvent;