ReduceStore.js 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. var Class = require('./Class');
  2. var clone = require('./clone');
  3. var remove = require('./remove');
  4. exports = Class({
  5. initialize: function ReduceStore(reducer, initialState) {
  6. this._reducer = reducer;
  7. this._state = initialState;
  8. this._curListeners = [];
  9. this._nextListeners = this._curListeners;
  10. },
  11. subscribe: function(listener) {
  12. var isSubscribed = true;
  13. this._ensureCanMutateNextListeners();
  14. this._nextListeners.push(listener);
  15. var self = this;
  16. return function() {
  17. if (!isSubscribed) return;
  18. isSubscribed = false;
  19. self._ensureCanMutateNextListeners();
  20. remove(self._nextListeners, function(val) {
  21. return val === listener;
  22. });
  23. };
  24. },
  25. dispatch: function(action) {
  26. this._state = this._reducer(this._state, action);
  27. var listeners = (this._curListeners = this._nextListeners);
  28. for (var i = 0, len = listeners.length; i < len; i++) listeners[i]();
  29. return action;
  30. },
  31. getState: function() {
  32. return this._state;
  33. },
  34. _ensureCanMutateNextListeners: function() {
  35. if (this._nextListeners === this._curListeners) {
  36. this._nextListeners = clone(this._curListeners);
  37. }
  38. }
  39. });
  40. module.exports = exports;