FromEventObservable.js 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203
  1. import { Observable } from '../Observable';
  2. import { tryCatch } from '../util/tryCatch';
  3. import { isFunction } from '../util/isFunction';
  4. import { errorObject } from '../util/errorObject';
  5. import { Subscription } from '../Subscription';
  6. const toString = Object.prototype.toString;
  7. function isNodeStyleEventEmitter(sourceObj) {
  8. return !!sourceObj && typeof sourceObj.addListener === 'function' && typeof sourceObj.removeListener === 'function';
  9. }
  10. function isJQueryStyleEventEmitter(sourceObj) {
  11. return !!sourceObj && typeof sourceObj.on === 'function' && typeof sourceObj.off === 'function';
  12. }
  13. function isNodeList(sourceObj) {
  14. return !!sourceObj && toString.call(sourceObj) === '[object NodeList]';
  15. }
  16. function isHTMLCollection(sourceObj) {
  17. return !!sourceObj && toString.call(sourceObj) === '[object HTMLCollection]';
  18. }
  19. function isEventTarget(sourceObj) {
  20. return !!sourceObj && typeof sourceObj.addEventListener === 'function' && typeof sourceObj.removeEventListener === 'function';
  21. }
  22. /**
  23. * We need this JSDoc comment for affecting ESDoc.
  24. * @extends {Ignored}
  25. * @hide true
  26. */
  27. export class FromEventObservable extends Observable {
  28. constructor(sourceObj, eventName, selector, options) {
  29. super();
  30. this.sourceObj = sourceObj;
  31. this.eventName = eventName;
  32. this.selector = selector;
  33. this.options = options;
  34. }
  35. /* tslint:enable:max-line-length */
  36. /**
  37. * Creates an Observable that emits events of a specific type coming from the
  38. * given event target.
  39. *
  40. * <span class="informal">Creates an Observable from DOM events, or Node.js
  41. * EventEmitter events or others.</span>
  42. *
  43. * <img src="./img/fromEvent.png" width="100%">
  44. *
  45. * `fromEvent` accepts as a first argument event target, which is an object with methods
  46. * for registering event handler functions. As a second argument it takes string that indicates
  47. * type of event we want to listen for. `fromEvent` supports selected types of event targets,
  48. * which are described in detail below. If your event target does not match any of the ones listed,
  49. * you should use {@link fromEventPattern}, which can be used on arbitrary APIs.
  50. * When it comes to APIs supported by `fromEvent`, their methods for adding and removing event
  51. * handler functions have different names, but they all accept a string describing event type
  52. * and function itself, which will be called whenever said event happens.
  53. *
  54. * Every time resulting Observable is subscribed, event handler function will be registered
  55. * to event target on given event type. When that event fires, value
  56. * passed as a first argument to registered function will be emitted by output Observable.
  57. * When Observable is unsubscribed, function will be unregistered from event target.
  58. *
  59. * Note that if event target calls registered function with more than one argument, second
  60. * and following arguments will not appear in resulting stream. In order to get access to them,
  61. * you can pass to `fromEvent` optional project function, which will be called with all arguments
  62. * passed to event handler. Output Observable will then emit value returned by project function,
  63. * instead of the usual value.
  64. *
  65. * Remember that event targets listed below are checked via duck typing. It means that
  66. * no matter what kind of object you have and no matter what environment you work in,
  67. * you can safely use `fromEvent` on that object if it exposes described methods (provided
  68. * of course they behave as was described above). So for example if Node.js library exposes
  69. * event target which has the same method names as DOM EventTarget, `fromEvent` is still
  70. * a good choice.
  71. *
  72. * If the API you use is more callback then event handler oriented (subscribed
  73. * callback function fires only once and thus there is no need to manually
  74. * unregister it), you should use {@link bindCallback} or {@link bindNodeCallback}
  75. * instead.
  76. *
  77. * `fromEvent` supports following types of event targets:
  78. *
  79. * **DOM EventTarget**
  80. *
  81. * This is an object with `addEventListener` and `removeEventListener` methods.
  82. *
  83. * In the browser, `addEventListener` accepts - apart from event type string and event
  84. * handler function arguments - optional third parameter, which is either an object or boolean,
  85. * both used for additional configuration how and when passed function will be called. When
  86. * `fromEvent` is used with event target of that type, you can provide this values
  87. * as third parameter as well.
  88. *
  89. * **Node.js EventEmitter**
  90. *
  91. * An object with `addListener` and `removeListener` methods.
  92. *
  93. * **JQuery-style event target**
  94. *
  95. * An object with `on` and `off` methods
  96. *
  97. * **DOM NodeList**
  98. *
  99. * List of DOM Nodes, returned for example by `document.querySelectorAll` or `Node.childNodes`.
  100. *
  101. * Although this collection is not event target in itself, `fromEvent` will iterate over all Nodes
  102. * it contains and install event handler function in every of them. When returned Observable
  103. * is unsubscribed, function will be removed from all Nodes.
  104. *
  105. * **DOM HtmlCollection**
  106. *
  107. * Just as in case of NodeList it is a collection of DOM nodes. Here as well event handler function is
  108. * installed and removed in each of elements.
  109. *
  110. *
  111. * @example <caption>Emits clicks happening on the DOM document</caption>
  112. * var clicks = Rx.Observable.fromEvent(document, 'click');
  113. * clicks.subscribe(x => console.log(x));
  114. *
  115. * // Results in:
  116. * // MouseEvent object logged to console every time a click
  117. * // occurs on the document.
  118. *
  119. *
  120. * @example <caption>Use addEventListener with capture option</caption>
  121. * var clicksInDocument = Rx.Observable.fromEvent(document, 'click', true); // note optional configuration parameter
  122. * // which will be passed to addEventListener
  123. * var clicksInDiv = Rx.Observable.fromEvent(someDivInDocument, 'click');
  124. *
  125. * clicksInDocument.subscribe(() => console.log('document'));
  126. * clicksInDiv.subscribe(() => console.log('div'));
  127. *
  128. * // By default events bubble UP in DOM tree, so normally
  129. * // when we would click on div in document
  130. * // "div" would be logged first and then "document".
  131. * // Since we specified optional `capture` option, document
  132. * // will catch event when it goes DOWN DOM tree, so console
  133. * // will log "document" and then "div".
  134. *
  135. * @see {@link bindCallback}
  136. * @see {@link bindNodeCallback}
  137. * @see {@link fromEventPattern}
  138. *
  139. * @param {EventTargetLike} target The DOM EventTarget, Node.js
  140. * EventEmitter, JQuery-like event target, NodeList or HTMLCollection to attach the event handler to.
  141. * @param {string} eventName The event name of interest, being emitted by the
  142. * `target`.
  143. * @param {EventListenerOptions} [options] Options to pass through to addEventListener
  144. * @param {SelectorMethodSignature<T>} [selector] An optional function to
  145. * post-process results. It takes the arguments from the event handler and
  146. * should return a single value.
  147. * @return {Observable<T>}
  148. * @static true
  149. * @name fromEvent
  150. * @owner Observable
  151. */
  152. static create(target, eventName, options, selector) {
  153. if (isFunction(options)) {
  154. selector = options;
  155. options = undefined;
  156. }
  157. return new FromEventObservable(target, eventName, selector, options);
  158. }
  159. static setupSubscription(sourceObj, eventName, handler, subscriber, options) {
  160. let unsubscribe;
  161. if (isNodeList(sourceObj) || isHTMLCollection(sourceObj)) {
  162. for (let i = 0, len = sourceObj.length; i < len; i++) {
  163. FromEventObservable.setupSubscription(sourceObj[i], eventName, handler, subscriber, options);
  164. }
  165. }
  166. else if (isEventTarget(sourceObj)) {
  167. const source = sourceObj;
  168. sourceObj.addEventListener(eventName, handler, options);
  169. unsubscribe = () => source.removeEventListener(eventName, handler, options);
  170. }
  171. else if (isJQueryStyleEventEmitter(sourceObj)) {
  172. const source = sourceObj;
  173. sourceObj.on(eventName, handler);
  174. unsubscribe = () => source.off(eventName, handler);
  175. }
  176. else if (isNodeStyleEventEmitter(sourceObj)) {
  177. const source = sourceObj;
  178. sourceObj.addListener(eventName, handler);
  179. unsubscribe = () => source.removeListener(eventName, handler);
  180. }
  181. else {
  182. throw new TypeError('Invalid event target');
  183. }
  184. subscriber.add(new Subscription(unsubscribe));
  185. }
  186. /** @deprecated internal use only */ _subscribe(subscriber) {
  187. const sourceObj = this.sourceObj;
  188. const eventName = this.eventName;
  189. const options = this.options;
  190. const selector = this.selector;
  191. let handler = selector ? (...args) => {
  192. let result = tryCatch(selector)(...args);
  193. if (result === errorObject) {
  194. subscriber.error(errorObject.e);
  195. }
  196. else {
  197. subscriber.next(result);
  198. }
  199. } : (e) => subscriber.next(e);
  200. FromEventObservable.setupSubscription(sourceObj, eventName, handler, subscriber, options);
  201. }
  202. }
  203. //# sourceMappingURL=FromEventObservable.js.map