Reputation: 245
I am reading the source code of redux.
anyone could help me understand the the function under createStore here?
It seems it implemented another version of observer pattern.
questions:
I didn't found any codes called this function, why the code appears here. what is the purpose? 2. how to call this function by store (the key is generated by 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;
}
fake code:
we need something like
var store$= store[$$observable]()
to get the observable. and anyone want to be notified when state changed, need to do
store$.subscribe(observer);
but now. I can't get the store[$$observable]
Upvotes: 1
Views: 287
Reputation: 245
after a few test:
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);
do not make the breakpoint to see the runtime value. undefined sometimes. but you can use it actually.
log:
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
Upvotes: 1