Created
June 7, 2022 04:48
-
-
Save bepyan/4228d901d4f241a9f9ab4ccec5383a23 to your computer and use it in GitHub Desktop.
vanillaJS core util - global state
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
export default class Store { | |
#state = {}; | |
#listeners = []; | |
#reducer; | |
/** | |
* 액션을 수행하고 새로운 state를 반환한다. dispatch를 통해 원하는 액션을 수행할 수 있다. | |
* @param {{}} state | |
* @param {{ payload: {} }} reducer | |
const reducer = (state, actionKey, { payload = {} }) => { | |
switch (actionKey) { | |
case "ACTION_TEST": | |
console.log(payload); | |
return { ...state }; | |
default: | |
return { ...state }; | |
} | |
}; | |
*/ | |
constructor(state, reducer) { | |
this.#state = state; | |
this.#reducer = reducer; | |
} | |
getState() { | |
return { ...this.#state }; | |
} | |
subscribe(func) { | |
this.#listeners.push(func); | |
} | |
publish() { | |
this.#listeners.forEach((func) => func()); | |
} | |
/** | |
* @param {string} actionKey | |
*/ | |
async dispatch(actionKey, { ...payload } = {}) { | |
this.#state = await this.#reducer(this.#state, actionKey, { ...payload }); | |
this.publish(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment