Dispatcher.js 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. var Class = require('./Class');
  2. var uniqId = require('./uniqId');
  3. exports = Class({
  4. initialize: function Dispatcher() {
  5. this._callbacks = {};
  6. this._isDispatching = false;
  7. this._isHandled = {};
  8. this._isPending = {};
  9. },
  10. dispatch: function(payload) {
  11. this._startDispatching(payload);
  12. for (var id in this._callbacks) {
  13. if (this._isPending[id]) continue;
  14. this._invokeCb(id);
  15. }
  16. this._stopDispatching();
  17. },
  18. register: function(cb) {
  19. var id = uniqId('ID_');
  20. this._callbacks[id] = cb;
  21. return id;
  22. },
  23. waitFor: function(ids) {
  24. for (var i = 0, len = ids.length; i < len; i++) {
  25. var id = ids[i];
  26. if (this._isPending[id]) continue;
  27. this._invokeCb(id);
  28. }
  29. },
  30. unregister: function(id) {
  31. delete this._callbacks[id];
  32. },
  33. isDispatching: function() {
  34. return this._isDispatching;
  35. },
  36. _startDispatching: function(payload) {
  37. for (var id in this._callbacks) {
  38. this._isPending[id] = false;
  39. this._isHandled[id] = false;
  40. }
  41. this._pendingPayload = payload;
  42. this._isDispatching = true;
  43. },
  44. _stopDispatching: function() {
  45. delete this._pendingPayload;
  46. this._isDispatching = false;
  47. },
  48. _invokeCb: function(id) {
  49. this._isPending[id] = true;
  50. this._callbacks[id](this._pendingPayload);
  51. this._isHandled[id] = true;
  52. }
  53. });
  54. module.exports = exports;