DefaultStore.js 792 B

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. /**
  2. * Default store that keeps state in a simple object.
  3. */
  4. class DefaultStore {
  5. constructor () {
  6. this.state = {}
  7. this.callbacks = []
  8. }
  9. getState () {
  10. return this.state
  11. }
  12. setState (patch) {
  13. const prevState = Object.assign({}, this.state)
  14. const nextState = Object.assign({}, this.state, patch)
  15. this.state = nextState
  16. this._publish(prevState, nextState, patch)
  17. }
  18. subscribe (listener) {
  19. this.callbacks.push(listener)
  20. return () => {
  21. // Remove the listener.
  22. this.callbacks.splice(
  23. this.callbacks.indexOf(listener),
  24. 1
  25. )
  26. }
  27. }
  28. _publish (...args) {
  29. this.callbacks.forEach((listener) => {
  30. listener(...args)
  31. })
  32. }
  33. }
  34. module.exports = function defaultStore () {
  35. return new DefaultStore()
  36. }