You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

41 lines
1011 B

  1. function createBroadcast (initialState) {
  2. var listeners = {};
  3. var id = 1;
  4. var _state = initialState;
  5. function getState () {
  6. return _state
  7. }
  8. function setState (state) {
  9. _state = state;
  10. var keys = Object.keys(listeners);
  11. var i = 0;
  12. var 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. var 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: getState, setState: setState, subscribe: subscribe, unsubscribe: unsubscribe }
  33. }
  34. export default createBroadcast;