Last active
July 21, 2021 12:25
-
-
Save hayoung123/5bcb25857b06d9a0de29cbc8a80f7021 to your computer and use it in GitHub Desktop.
옵저버 함수형으로 관리하기
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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