rx.binding.js 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561
  1. // Copyright (c) Microsoft, All rights reserved. See License.txt in the project root for license information.
  2. ;(function (factory) {
  3. var objectTypes = {
  4. 'function': true,
  5. 'object': true
  6. };
  7. function checkGlobal(value) {
  8. return (value && value.Object === Object) ? value : null;
  9. }
  10. var freeExports = (objectTypes[typeof exports] && exports && !exports.nodeType) ? exports : null;
  11. var freeModule = (objectTypes[typeof module] && module && !module.nodeType) ? module : null;
  12. var freeGlobal = checkGlobal(freeExports && freeModule && typeof global === 'object' && global);
  13. var freeSelf = checkGlobal(objectTypes[typeof self] && self);
  14. var freeWindow = checkGlobal(objectTypes[typeof window] && window);
  15. var moduleExports = (freeModule && freeModule.exports === freeExports) ? freeExports : null;
  16. var thisGlobal = checkGlobal(objectTypes[typeof this] && this);
  17. var root = freeGlobal || ((freeWindow !== (thisGlobal && thisGlobal.window)) && freeWindow) || freeSelf || thisGlobal || Function('return this')();
  18. // Because of build optimizers
  19. if (typeof define === 'function' && define.amd) {
  20. define(['./rx'], function (Rx, exports) {
  21. return factory(root, exports, Rx);
  22. });
  23. } else if (typeof module === 'object' && module && module.exports === freeExports) {
  24. module.exports = factory(root, module.exports, require('./rx'));
  25. } else {
  26. root.Rx = factory(root, {}, root.Rx);
  27. }
  28. }.call(this, function (root, exp, Rx, undefined) {
  29. var Observable = Rx.Observable,
  30. observableProto = Observable.prototype,
  31. AnonymousObservable = Rx.AnonymousObservable,
  32. ObservableBase = Rx.ObservableBase,
  33. Subject = Rx.Subject,
  34. AsyncSubject = Rx.AsyncSubject,
  35. Observer = Rx.Observer,
  36. ScheduledObserver = Rx.internals.ScheduledObserver,
  37. disposableCreate = Rx.Disposable.create,
  38. disposableEmpty = Rx.Disposable.empty,
  39. BinaryDisposable = Rx.BinaryDisposable,
  40. currentThreadScheduler = Rx.Scheduler.currentThread,
  41. isFunction = Rx.helpers.isFunction,
  42. inherits = Rx.internals.inherits,
  43. addProperties = Rx.internals.addProperties,
  44. checkDisposed = Rx.Disposable.checkDisposed;
  45. // Utilities
  46. function cloneArray(arr) {
  47. var len = arr.length, a = new Array(len);
  48. for(var i = 0; i < len; i++) { a[i] = arr[i]; }
  49. return a;
  50. }
  51. var MulticastObservable = (function (__super__) {
  52. inherits(MulticastObservable, __super__);
  53. function MulticastObservable(source, fn1, fn2) {
  54. this.source = source;
  55. this._fn1 = fn1;
  56. this._fn2 = fn2;
  57. __super__.call(this);
  58. }
  59. MulticastObservable.prototype.subscribeCore = function (o) {
  60. var connectable = this.source.multicast(this._fn1());
  61. return new BinaryDisposable(this._fn2(connectable).subscribe(o), connectable.connect());
  62. };
  63. return MulticastObservable;
  64. }(ObservableBase));
  65. /**
  66. * Multicasts the source sequence notifications through an instantiated subject into all uses of the sequence within a selector function. Each
  67. * subscription to the resulting sequence causes a separate multicast invocation, exposing the sequence resulting from the selector function's
  68. * invocation. For specializations with fixed subject types, see Publish, PublishLast, and Replay.
  69. *
  70. * @example
  71. * 1 - res = source.multicast(observable);
  72. * 2 - res = source.multicast(function () { return new Subject(); }, function (x) { return x; });
  73. *
  74. * @param {Function|Subject} subjectOrSubjectSelector
  75. * Factory function to create an intermediate subject through which the source sequence's elements will be multicast to the selector function.
  76. * Or:
  77. * Subject to push source elements into.
  78. *
  79. * @param {Function} [selector] Optional selector function which can use the multicasted source sequence subject to the policies enforced by the created subject. Specified only if <paramref name="subjectOrSubjectSelector" is a factory function.
  80. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function.
  81. */
  82. observableProto.multicast = function (subjectOrSubjectSelector, selector) {
  83. return isFunction(subjectOrSubjectSelector) ?
  84. new MulticastObservable(this, subjectOrSubjectSelector, selector) :
  85. new ConnectableObservable(this, subjectOrSubjectSelector);
  86. };
  87. /**
  88. * Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence.
  89. * This operator is a specialization of Multicast using a regular Subject.
  90. *
  91. * @example
  92. * var resres = source.publish();
  93. * var res = source.publish(function (x) { return x; });
  94. *
  95. * @param {Function} [selector] Selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will receive all notifications of the source from the time of the subscription on.
  96. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function.
  97. */
  98. observableProto.publish = function (selector) {
  99. return selector && isFunction(selector) ?
  100. this.multicast(function () { return new Subject(); }, selector) :
  101. this.multicast(new Subject());
  102. };
  103. /**
  104. * Returns an observable sequence that shares a single subscription to the underlying sequence.
  105. * This operator is a specialization of publish which creates a subscription when the number of observers goes from zero to one, then shares that subscription with all subsequent observers until the number of observers returns to zero, at which point the subscription is disposed.
  106. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence.
  107. */
  108. observableProto.share = function () {
  109. return this.publish().refCount();
  110. };
  111. /**
  112. * Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence containing only the last notification.
  113. * This operator is a specialization of Multicast using a AsyncSubject.
  114. *
  115. * @example
  116. * var res = source.publishLast();
  117. * var res = source.publishLast(function (x) { return x; });
  118. *
  119. * @param selector [Optional] Selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will only receive the last notification of the source.
  120. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function.
  121. */
  122. observableProto.publishLast = function (selector) {
  123. return selector && isFunction(selector) ?
  124. this.multicast(function () { return new AsyncSubject(); }, selector) :
  125. this.multicast(new AsyncSubject());
  126. };
  127. /**
  128. * Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence and starts with initialValue.
  129. * This operator is a specialization of Multicast using a BehaviorSubject.
  130. *
  131. * @example
  132. * var res = source.publishValue(42);
  133. * var res = source.publishValue(function (x) { return x.select(function (y) { return y * y; }) }, 42);
  134. *
  135. * @param {Function} [selector] Optional selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will receive immediately receive the initial value, followed by all notifications of the source from the time of the subscription on.
  136. * @param {Mixed} initialValue Initial value received by observers upon subscription.
  137. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function.
  138. */
  139. observableProto.publishValue = function (initialValueOrSelector, initialValue) {
  140. return arguments.length === 2 ?
  141. this.multicast(function () {
  142. return new BehaviorSubject(initialValue);
  143. }, initialValueOrSelector) :
  144. this.multicast(new BehaviorSubject(initialValueOrSelector));
  145. };
  146. /**
  147. * Returns an observable sequence that shares a single subscription to the underlying sequence and starts with an initialValue.
  148. * This operator is a specialization of publishValue which creates a subscription when the number of observers goes from zero to one, then shares that subscription with all subsequent observers until the number of observers returns to zero, at which point the subscription is disposed.
  149. * @param {Mixed} initialValue Initial value received by observers upon subscription.
  150. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence.
  151. */
  152. observableProto.shareValue = function (initialValue) {
  153. return this.publishValue(initialValue).refCount();
  154. };
  155. /**
  156. * Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence replaying notifications subject to a maximum time length for the replay buffer.
  157. * This operator is a specialization of Multicast using a ReplaySubject.
  158. *
  159. * @example
  160. * var res = source.replay(null, 3);
  161. * var res = source.replay(null, 3, 500);
  162. * var res = source.replay(null, 3, 500, scheduler);
  163. * var res = source.replay(function (x) { return x.take(6).repeat(); }, 3, 500, scheduler);
  164. *
  165. * @param selector [Optional] Selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will receive all the notifications of the source subject to the specified replay buffer trimming policy.
  166. * @param bufferSize [Optional] Maximum element count of the replay buffer.
  167. * @param windowSize [Optional] Maximum time length of the replay buffer.
  168. * @param scheduler [Optional] Scheduler where connected observers within the selector function will be invoked on.
  169. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function.
  170. */
  171. observableProto.replay = function (selector, bufferSize, windowSize, scheduler) {
  172. return selector && isFunction(selector) ?
  173. this.multicast(function () { return new ReplaySubject(bufferSize, windowSize, scheduler); }, selector) :
  174. this.multicast(new ReplaySubject(bufferSize, windowSize, scheduler));
  175. };
  176. /**
  177. * Returns an observable sequence that shares a single subscription to the underlying sequence replaying notifications subject to a maximum time length for the replay buffer.
  178. * This operator is a specialization of replay which creates a subscription when the number of observers goes from zero to one, then shares that subscription with all subsequent observers until the number of observers returns to zero, at which point the subscription is disposed.
  179. *
  180. * @example
  181. * var res = source.shareReplay(3);
  182. * var res = source.shareReplay(3, 500);
  183. * var res = source.shareReplay(3, 500, scheduler);
  184. *
  185. * @param bufferSize [Optional] Maximum element count of the replay buffer.
  186. * @param window [Optional] Maximum time length of the replay buffer.
  187. * @param scheduler [Optional] Scheduler where connected observers within the selector function will be invoked on.
  188. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence.
  189. */
  190. observableProto.shareReplay = function (bufferSize, windowSize, scheduler) {
  191. return this.replay(null, bufferSize, windowSize, scheduler).refCount();
  192. };
  193. var InnerSubscription = function (s, o) {
  194. this._s = s;
  195. this._o = o;
  196. };
  197. InnerSubscription.prototype.dispose = function () {
  198. if (!this._s.isDisposed && this._o !== null) {
  199. var idx = this._s.observers.indexOf(this._o);
  200. this._s.observers.splice(idx, 1);
  201. this._o = null;
  202. }
  203. };
  204. /**
  205. * Represents a value that changes over time.
  206. * Observers can subscribe to the subject to receive the last (or initial) value and all subsequent notifications.
  207. */
  208. var BehaviorSubject = Rx.BehaviorSubject = (function (__super__) {
  209. inherits(BehaviorSubject, __super__);
  210. function BehaviorSubject(value) {
  211. __super__.call(this);
  212. this.value = value;
  213. this.observers = [];
  214. this.isDisposed = false;
  215. this.isStopped = false;
  216. this.hasError = false;
  217. }
  218. addProperties(BehaviorSubject.prototype, Observer.prototype, {
  219. _subscribe: function (o) {
  220. checkDisposed(this);
  221. if (!this.isStopped) {
  222. this.observers.push(o);
  223. o.onNext(this.value);
  224. return new InnerSubscription(this, o);
  225. }
  226. if (this.hasError) {
  227. o.onError(this.error);
  228. } else {
  229. o.onCompleted();
  230. }
  231. return disposableEmpty;
  232. },
  233. /**
  234. * Gets the current value or throws an exception.
  235. * Value is frozen after onCompleted is called.
  236. * After onError is called always throws the specified exception.
  237. * An exception is always thrown after dispose is called.
  238. * @returns {Mixed} The initial value passed to the constructor until onNext is called; after which, the last value passed to onNext.
  239. */
  240. getValue: function () {
  241. checkDisposed(this);
  242. if (this.hasError) { thrower(this.error); }
  243. return this.value;
  244. },
  245. /**
  246. * Indicates whether the subject has observers subscribed to it.
  247. * @returns {Boolean} Indicates whether the subject has observers subscribed to it.
  248. */
  249. hasObservers: function () { checkDisposed(this); return this.observers.length > 0; },
  250. /**
  251. * Notifies all subscribed observers about the end of the sequence.
  252. */
  253. onCompleted: function () {
  254. checkDisposed(this);
  255. if (this.isStopped) { return; }
  256. this.isStopped = true;
  257. for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) {
  258. os[i].onCompleted();
  259. }
  260. this.observers.length = 0;
  261. },
  262. /**
  263. * Notifies all subscribed observers about the exception.
  264. * @param {Mixed} error The exception to send to all observers.
  265. */
  266. onError: function (error) {
  267. checkDisposed(this);
  268. if (this.isStopped) { return; }
  269. this.isStopped = true;
  270. this.hasError = true;
  271. this.error = error;
  272. for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) {
  273. os[i].onError(error);
  274. }
  275. this.observers.length = 0;
  276. },
  277. /**
  278. * Notifies all subscribed observers about the arrival of the specified element in the sequence.
  279. * @param {Mixed} value The value to send to all observers.
  280. */
  281. onNext: function (value) {
  282. checkDisposed(this);
  283. if (this.isStopped) { return; }
  284. this.value = value;
  285. for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) {
  286. os[i].onNext(value);
  287. }
  288. },
  289. /**
  290. * Unsubscribe all observers and release resources.
  291. */
  292. dispose: function () {
  293. this.isDisposed = true;
  294. this.observers = null;
  295. this.value = null;
  296. this.error = null;
  297. }
  298. });
  299. return BehaviorSubject;
  300. }(Observable));
  301. /**
  302. * Represents an object that is both an observable sequence as well as an observer.
  303. * Each notification is broadcasted to all subscribed and future observers, subject to buffer trimming policies.
  304. */
  305. var ReplaySubject = Rx.ReplaySubject = (function (__super__) {
  306. var maxSafeInteger = Math.pow(2, 53) - 1;
  307. function createRemovableDisposable(subject, observer) {
  308. return disposableCreate(function () {
  309. observer.dispose();
  310. !subject.isDisposed && subject.observers.splice(subject.observers.indexOf(observer), 1);
  311. });
  312. }
  313. inherits(ReplaySubject, __super__);
  314. /**
  315. * Initializes a new instance of the ReplaySubject class with the specified buffer size, window size and scheduler.
  316. * @param {Number} [bufferSize] Maximum element count of the replay buffer.
  317. * @param {Number} [windowSize] Maximum time length of the replay buffer.
  318. * @param {Scheduler} [scheduler] Scheduler the observers are invoked on.
  319. */
  320. function ReplaySubject(bufferSize, windowSize, scheduler) {
  321. this.bufferSize = bufferSize == null ? maxSafeInteger : bufferSize;
  322. this.windowSize = windowSize == null ? maxSafeInteger : windowSize;
  323. this.scheduler = scheduler || currentThreadScheduler;
  324. this.q = [];
  325. this.observers = [];
  326. this.isStopped = false;
  327. this.isDisposed = false;
  328. this.hasError = false;
  329. this.error = null;
  330. __super__.call(this);
  331. }
  332. addProperties(ReplaySubject.prototype, Observer.prototype, {
  333. _subscribe: function (o) {
  334. checkDisposed(this);
  335. var so = new ScheduledObserver(this.scheduler, o), subscription = createRemovableDisposable(this, so);
  336. this._trim(this.scheduler.now());
  337. this.observers.push(so);
  338. for (var i = 0, len = this.q.length; i < len; i++) {
  339. so.onNext(this.q[i].value);
  340. }
  341. if (this.hasError) {
  342. so.onError(this.error);
  343. } else if (this.isStopped) {
  344. so.onCompleted();
  345. }
  346. so.ensureActive();
  347. return subscription;
  348. },
  349. /**
  350. * Indicates whether the subject has observers subscribed to it.
  351. * @returns {Boolean} Indicates whether the subject has observers subscribed to it.
  352. */
  353. hasObservers: function () { checkDisposed(this); return this.observers.length > 0; },
  354. _trim: function (now) {
  355. while (this.q.length > this.bufferSize) {
  356. this.q.shift();
  357. }
  358. while (this.q.length > 0 && (now - this.q[0].interval) > this.windowSize) {
  359. this.q.shift();
  360. }
  361. },
  362. /**
  363. * Notifies all subscribed observers about the arrival of the specified element in the sequence.
  364. * @param {Mixed} value The value to send to all observers.
  365. */
  366. onNext: function (value) {
  367. checkDisposed(this);
  368. if (this.isStopped) { return; }
  369. var now = this.scheduler.now();
  370. this.q.push({ interval: now, value: value });
  371. this._trim(now);
  372. for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) {
  373. var observer = os[i];
  374. observer.onNext(value);
  375. observer.ensureActive();
  376. }
  377. },
  378. /**
  379. * Notifies all subscribed observers about the exception.
  380. * @param {Mixed} error The exception to send to all observers.
  381. */
  382. onError: function (error) {
  383. checkDisposed(this);
  384. if (this.isStopped) { return; }
  385. this.isStopped = true;
  386. this.error = error;
  387. this.hasError = true;
  388. var now = this.scheduler.now();
  389. this._trim(now);
  390. for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) {
  391. var observer = os[i];
  392. observer.onError(error);
  393. observer.ensureActive();
  394. }
  395. this.observers.length = 0;
  396. },
  397. /**
  398. * Notifies all subscribed observers about the end of the sequence.
  399. */
  400. onCompleted: function () {
  401. checkDisposed(this);
  402. if (this.isStopped) { return; }
  403. this.isStopped = true;
  404. var now = this.scheduler.now();
  405. this._trim(now);
  406. for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) {
  407. var observer = os[i];
  408. observer.onCompleted();
  409. observer.ensureActive();
  410. }
  411. this.observers.length = 0;
  412. },
  413. /**
  414. * Unsubscribe all observers and release resources.
  415. */
  416. dispose: function () {
  417. this.isDisposed = true;
  418. this.observers = null;
  419. }
  420. });
  421. return ReplaySubject;
  422. }(Observable));
  423. var RefCountObservable = (function (__super__) {
  424. inherits(RefCountObservable, __super__);
  425. function RefCountObservable(source) {
  426. this.source = source;
  427. this._count = 0;
  428. this._connectableSubscription = null;
  429. __super__.call(this);
  430. }
  431. RefCountObservable.prototype.subscribeCore = function (o) {
  432. var subscription = this.source.subscribe(o);
  433. ++this._count === 1 && (this._connectableSubscription = this.source.connect());
  434. return new RefCountDisposable(this, subscription);
  435. };
  436. function RefCountDisposable(p, s) {
  437. this._p = p;
  438. this._s = s;
  439. this.isDisposed = false;
  440. }
  441. RefCountDisposable.prototype.dispose = function () {
  442. if (!this.isDisposed) {
  443. this.isDisposed = true;
  444. this._s.dispose();
  445. --this._p._count === 0 && this._p._connectableSubscription.dispose();
  446. }
  447. };
  448. return RefCountObservable;
  449. }(ObservableBase));
  450. var ConnectableObservable = Rx.ConnectableObservable = (function (__super__) {
  451. inherits(ConnectableObservable, __super__);
  452. function ConnectableObservable(source, subject) {
  453. this.source = source;
  454. this._connection = null;
  455. this._source = source.asObservable();
  456. this._subject = subject;
  457. __super__.call(this);
  458. }
  459. function ConnectDisposable(parent, subscription) {
  460. this._p = parent;
  461. this._s = subscription;
  462. }
  463. ConnectDisposable.prototype.dispose = function () {
  464. if (this._s) {
  465. this._s.dispose();
  466. this._s = null;
  467. this._p._connection = null;
  468. }
  469. };
  470. ConnectableObservable.prototype.connect = function () {
  471. if (!this._connection) {
  472. if (this._subject.isStopped) {
  473. return disposableEmpty;
  474. }
  475. var subscription = this._source.subscribe(this._subject);
  476. this._connection = new ConnectDisposable(this, subscription);
  477. }
  478. return this._connection;
  479. };
  480. ConnectableObservable.prototype._subscribe = function (o) {
  481. return this._subject.subscribe(o);
  482. };
  483. ConnectableObservable.prototype.refCount = function () {
  484. return new RefCountObservable(this);
  485. };
  486. return ConnectableObservable;
  487. }(Observable));
  488. /**
  489. * Returns an observable sequence that shares a single subscription to the underlying sequence. This observable sequence
  490. * can be resubscribed to, even if all prior subscriptions have ended. (unlike `.publish().refCount()`)
  491. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source.
  492. */
  493. observableProto.singleInstance = function() {
  494. var source = this, hasObservable = false, observable;
  495. function getObservable() {
  496. if (!hasObservable) {
  497. hasObservable = true;
  498. observable = source['finally'](function() { hasObservable = false; }).publish().refCount();
  499. }
  500. return observable;
  501. }
  502. return new AnonymousObservable(function(o) {
  503. return getObservable().subscribe(o);
  504. });
  505. };
  506. return Rx;
  507. }));