2019-01-12 11:33:27 +08:00
|
|
|
export default function create(initialState) {
|
|
|
|
let state = initialState;
|
|
|
|
const listeners = [];
|
2018-03-25 18:07:04 +08:00
|
|
|
|
2019-01-12 11:33:27 +08:00
|
|
|
function setState(partial) {
|
|
|
|
state = { ...state, ...partial };
|
2018-03-25 18:07:04 +08:00
|
|
|
for (let i = 0; i < listeners.length; i++) {
|
2019-01-12 11:33:27 +08:00
|
|
|
listeners[i]();
|
2018-03-25 18:07:04 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-01-12 11:33:27 +08:00
|
|
|
function getState() {
|
|
|
|
return state;
|
2018-03-25 18:07:04 +08:00
|
|
|
}
|
|
|
|
|
2019-01-12 11:33:27 +08:00
|
|
|
function subscribe(listener) {
|
|
|
|
listeners.push(listener);
|
2018-03-25 18:07:04 +08:00
|
|
|
|
2019-01-12 11:33:27 +08:00
|
|
|
return function unsubscribe() {
|
|
|
|
const index = listeners.indexOf(listener);
|
|
|
|
listeners.splice(index, 1);
|
|
|
|
};
|
2018-03-25 18:07:04 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
return {
|
|
|
|
setState,
|
|
|
|
getState,
|
|
|
|
subscribe,
|
2019-01-12 11:33:27 +08:00
|
|
|
};
|
2018-03-25 18:07:04 +08:00
|
|
|
}
|