FromEventObservable.js 10 KB

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