-
-
Save reime005/ac59255663e93012dc0f51dc1375ac7c 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 actionTypes = { | |
ACTION_TYPE_TEST: 'ACTION_TYPE_TEST' | |
} | |
class Store { | |
constructor(initialState = { testValue: 0 }) { | |
this.state = initialState; | |
this.subscribers = []; | |
} | |
dispatch(action) { | |
this.state = reducer(this.state, action); | |
this.notifySubscribers(); | |
return action; | |
} | |
notifySubscribers() { | |
this.subscribers.forEach(subscriber => { | |
subscriber(this.state); | |
}); | |
} | |
subscribe(fn) { | |
this.subscribers.push(fn); | |
} | |
getState() { | |
return this.state; | |
} | |
} | |
const reducer = (state, { type, payload }) => { | |
switch (type) { | |
case actionTypes.ACTION_TYPE_TEST: { | |
return { | |
...state, | |
testValue: payload | |
} | |
} | |
default: { | |
return state; | |
} | |
} | |
} | |
const myStore = new Store(); // 0 | |
myStore.subscribe(newState => console.warn(newState)); | |
console.warn(myStore.getState().testValue); | |
myStore.dispatch({ type: actionTypes.ACTION_TYPE_TEST, payload: 42 }); | |
console.warn(myStore.getState().testValue); // 42 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment