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.
 
 
 
 

49 lines
1.2 KiB

  1. (function (global, factory) {
  2. typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
  3. typeof define === 'function' && define.amd ? define(factory) :
  4. (global.brcast = factory());
  5. }(this, (function () {
  6. function createBroadcast (initialState) {
  7. var listeners = {};
  8. var id = 1;
  9. var _state = initialState;
  10. function getState () {
  11. return _state
  12. }
  13. function setState (state) {
  14. _state = state;
  15. var keys = Object.keys(listeners);
  16. var i = 0;
  17. var len = keys.length;
  18. for (; i < len; i++) {
  19. // if a listener gets unsubscribed during setState we just skip it
  20. if (listeners[keys[i]]) { listeners[keys[i]](state); }
  21. }
  22. }
  23. // subscribe to changes and return the subscriptionId
  24. function subscribe (listener) {
  25. if (typeof listener !== 'function') {
  26. throw new Error('listener must be a function.')
  27. }
  28. var currentId = id;
  29. listeners[currentId] = listener;
  30. id += 1;
  31. return currentId
  32. }
  33. // remove subscription by removing the listener function
  34. function unsubscribe (id) {
  35. listeners[id] = undefined;
  36. }
  37. return { getState: getState, setState: setState, subscribe: subscribe, unsubscribe: unsubscribe }
  38. }
  39. return createBroadcast;
  40. })));