Skip to content

Instantly share code, notes, and snippets.

@hayoung123
Last active July 21, 2021 12:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hayoung123/5bcb25857b06d9a0de29cbc8a80f7021 to your computer and use it in GitHub Desktop.
Save hayoung123/5bcb25857b06d9a0de29cbc8a80f7021 to your computer and use it in GitHub Desktop.
옵저버 함수형으로 관리하기
const globalState = {};
const subscribe = (key, className, observer) => globalState[key]._observers.set(className, observer);
const unsubscribe = (key,className,observer) => globalState[key]._observers.remove(className, observer);
const _notify = (key) => globalState[key]._observers.forEach((observer) => observer());
const initState = ({ key, defaultValue }) => {
if (key in globalState) throw Error('이미 존재하는 key값 입니다.');
globalState[key] = {
_state: defaultValue,
_observers: new Map(),
};
return key;
};
const getState = (key) => {
if (!(key in globalState)) throw Error('존재하지 않는 key값 입니다.');
return globalState[key]._state;
};
const setState = (key) => (newState) => {
if (!(key in globalState)) throw Error('존재하지 않는 key값 입니다.');
if (typeof newState === 'function') {
const state = getState(key);
globalState[key]._state = newState(state);
} else {
globalState[key]._state = newState;
}
_notify(key);
};
export { subscribe, initState, getState, setState };
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment