123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133 |
- "use strict";
- exports.__esModule = true;
- exports.createSubscription = createSubscription;
- var _batch = require("./batch");
- // encapsulates the subscription logic for connecting a component to the redux store, as
- // well as nesting subscriptions of descendant components, so that we can ensure the
- // ancestor components re-render before descendants
- function createListenerCollection() {
- var batch = (0, _batch.getBatch)();
- var first = null;
- var last = null;
- return {
- clear: function clear() {
- first = null;
- last = null;
- },
- notify: function notify() {
- batch(function () {
- var listener = first;
- while (listener) {
- listener.callback();
- listener = listener.next;
- }
- });
- },
- get: function get() {
- var listeners = [];
- var listener = first;
- while (listener) {
- listeners.push(listener);
- listener = listener.next;
- }
- return listeners;
- },
- subscribe: function subscribe(callback) {
- var isSubscribed = true;
- var listener = last = {
- callback: callback,
- next: null,
- prev: last
- };
- if (listener.prev) {
- listener.prev.next = listener;
- } else {
- first = listener;
- }
- return function unsubscribe() {
- if (!isSubscribed || first === null) return;
- isSubscribed = false;
- if (listener.next) {
- listener.next.prev = listener.prev;
- } else {
- last = listener.prev;
- }
- if (listener.prev) {
- listener.prev.next = listener.next;
- } else {
- first = listener.next;
- }
- };
- }
- };
- }
- var nullListeners = {
- notify: function notify() {},
- get: function get() {
- return [];
- }
- };
- function createSubscription(store, parentSub) {
- var unsubscribe;
- var listeners = nullListeners;
- function addNestedSub(listener) {
- trySubscribe();
- return listeners.subscribe(listener);
- }
- function notifyNestedSubs() {
- listeners.notify();
- }
- function handleChangeWrapper() {
- if (subscription.onStateChange) {
- subscription.onStateChange();
- }
- }
- function isSubscribed() {
- return Boolean(unsubscribe);
- }
- function trySubscribe() {
- if (!unsubscribe) {
- unsubscribe = parentSub ? parentSub.addNestedSub(handleChangeWrapper) : store.subscribe(handleChangeWrapper);
- listeners = createListenerCollection();
- }
- }
- function tryUnsubscribe() {
- if (unsubscribe) {
- unsubscribe();
- unsubscribe = undefined;
- listeners.clear();
- listeners = nullListeners;
- }
- }
- var subscription = {
- addNestedSub: addNestedSub,
- notifyNestedSubs: notifyNestedSubs,
- handleChangeWrapper: handleChangeWrapper,
- isSubscribed: isSubscribed,
- trySubscribe: trySubscribe,
- tryUnsubscribe: tryUnsubscribe,
- getListeners: function getListeners() {
- return listeners;
- }
- };
- return subscription;
- }
|