DeepFrozenStore.js 908 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. const deepFreeze = require('deep-freeze')
  2. /* eslint-disable no-underscore-dangle */
  3. /**
  4. * Default store + deepFreeze on setState to make sure nothing is mutated accidentally
  5. */
  6. class DeepFrozenStore {
  7. constructor () {
  8. this.state = {}
  9. this.callbacks = []
  10. }
  11. getState () {
  12. return this.state
  13. }
  14. setState (patch) {
  15. const prevState = { ...this.state }
  16. const nextState = deepFreeze({ ...this.state, ...patch })
  17. this.state = nextState
  18. this._publish(prevState, nextState, patch)
  19. }
  20. subscribe (listener) {
  21. this.callbacks.push(listener)
  22. return () => {
  23. // Remove the listener.
  24. this.callbacks.splice(
  25. this.callbacks.indexOf(listener),
  26. 1
  27. )
  28. }
  29. }
  30. _publish (...args) {
  31. this.callbacks.forEach((listener) => {
  32. listener(...args)
  33. })
  34. }
  35. }
  36. module.exports = function defaultStore () {
  37. return new DeepFrozenStore()
  38. }