Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- function createStore(reducer, initialState) {
- let currentState = initialState
- let currentReducer = reducer
- const listeners = []
- return {
- getState() {
- return currentState
- },
- dispatch(action) {
- currentState = currentReducer(currentState, action)
- listeners.forEach(fn => fn())
- return action
- },
- subscribe(newListener) {
- listeners.push(newListener)
- return () => listeners.splice(listeners.indexOf(newListener), 1)
- }
- }
- }
- function counter(state = 0, action) {
- switch (action.type) {
- case 'INCREMENT': return state + 1
- case 'DECREMENT': return state - 1
- default: return state
- }
- }
- let store = createStore(counter)
- const unsubscribe = store.subscribe(() => {
- console.log(store.getState())
- })
- store.dispatch({ type: 'INCREMENT' })
- store.dispatch({ type: 'DECREMENT' })
- unsubscribe()
- store.dispatch({ type: 'DECREMENT' })
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement