如何理解createStore下的observable函数

时间:2016-04-28 08:46:17

标签: redux

我正在阅读redux的源代码。

任何人都可以帮我理解createStore下的功能吗?

它似乎实现了另一个版本的观察者模式。

的问题:

我没有找到任何称为此函数的代码,为什么代码出现在此处。什么目的? 2.如何通过商店调用此函数(密钥由Symbole($$ observable)生成)

function observable() {
var _ref;

var outerSubscribe = subscribe;
return _ref = {
  /**
   * The minimal observable subscription method.
   * @param {Object} observer Any object that can be used as an observer.
   * The observer object should have a `next` method.
   * @returns {subscription} An object with an `unsubscribe` method that can
   * be used to unsubscribe the observable from the store, and prevent    further
   * emission of values from the observable.
   */

  subscribe: function subscribe(observer) {
    if (typeof observer !== 'object') {
      throw new TypeError('Expected the observer to be an object.');
    }

    function observeState() {
      if (observer.next) {
        observer.next(getState());
      }
    }

    observeState();
    var unsubscribe = outerSubscribe(observeState);
    return { unsubscribe: unsubscribe };
  }
}, _ref[$$observable] = function () {
  return this;
}, _ref;
}

// When a store is created, an "INIT" action is dispatched so that every
// reducer returns their initial state. This effectively populates
// the initial state tree.
dispatch({ type: ActionTypes.INIT });

return _ref2 = {
dispatch: dispatch,
subscribe: subscribe,
getState: getState,
replaceReducer: replaceReducer
 }, _ref2[$$observable] = observable, _ref2;
}

假代码:

我们需要像

这样的东西
 var store$= store[$$observable]() 

获得可观察性。 任何人都希望在州改变时得到通知,

商店$ .subscribe(观察者);

但是现在。我无法获得商店[$$ observable]

1 个答案:

答案 0 :(得分:1)

经过几次测试后

var x = window.Symbol.for('observable'); var y = store[x]; var z = y(); console.log(x); console.log(store[x]); console.log("y", y); console.log("z", z);

不要让断点看到运行时值。有时不确定。 但你可以实际使用它。

日志:

Symbol(observable)
main.tsx:138 observable() {
var _ref;

var outerSubscribe = subscribe;
return _ref = {
  /**
   * The minimal observable subscription method.
   * @param {Object} observer Any obje…
main.tsx:139 y observable() {
var _ref;

var outerSubscribe = subscribe;
return _ref = {
  /**
   * The minimal observable subscription method.
   * @param {Object} observer Any obje…
main.tsx:140 z Object {}subscribe: subscribe(observer)Symbol(observable): ()__proto__: Object