Advertisement
Guest User

Untitled

a guest
Apr 30th, 2017
64
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.88 KB | None | 0 0
  1. function createStore(reducer, initialState) {
  2. let currentState = initialState
  3. let currentReducer = reducer
  4. const listeners = []
  5.  
  6. return {
  7. getState() {
  8. return currentState
  9. },
  10. dispatch(action) {
  11. currentState = currentReducer(currentState, action)
  12. listeners.forEach(fn => fn())
  13. return action
  14. },
  15. subscribe(newListener) {
  16. listeners.push(newListener)
  17. return () => listeners.splice(listeners.indexOf(newListener), 1)
  18. }
  19. }
  20. }
  21.  
  22. function counter(state = 0, action) {
  23. switch (action.type) {
  24. case 'INCREMENT': return state + 1
  25. case 'DECREMENT': return state - 1
  26. default: return state
  27. }
  28. }
  29.  
  30. let store = createStore(counter)
  31.  
  32. const unsubscribe = store.subscribe(() => {
  33. console.log(store.getState())
  34. })
  35.  
  36. store.dispatch({ type: 'INCREMENT' })
  37. store.dispatch({ type: 'DECREMENT' })
  38. unsubscribe()
  39. store.dispatch({ type: 'DECREMENT' })
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement