Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

3 лет назад
1234567891011121314151617181920212223242526272829303132333435363738
  1. export default function createBroadcast (initialState) {
  2. let listeners = {}
  3. let id = 1
  4. let _state = initialState
  5. function getState () {
  6. return _state
  7. }
  8. function setState (state) {
  9. _state = state
  10. const keys = Object.keys(listeners)
  11. let i = 0
  12. const len = keys.length
  13. for (; i < len; i++) {
  14. // if a listener gets unsubscribed during setState we just skip it
  15. if (listeners[keys[i]]) listeners[keys[i]](state)
  16. }
  17. }
  18. // subscribe to changes and return the subscriptionId
  19. function subscribe (listener) {
  20. if (typeof listener !== 'function') {
  21. throw new Error('listener must be a function.')
  22. }
  23. const currentId = id
  24. listeners[currentId] = listener
  25. id += 1
  26. return currentId
  27. }
  28. // remove subscription by removing the listener function
  29. function unsubscribe (id) {
  30. listeners[id] = undefined
  31. }
  32. return { getState, setState, subscribe, unsubscribe }
  33. }