DeepFrozenStore.js 863 B

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