Store.ts 871 B

12345678910111213141516171819202122232425262728293031323334353637
  1. /* istanbul ignore next */
  2. class Store<T = Record<string, any>> {
  3. _state: T;
  4. _listeners: any[];
  5. constructor(initialState: T) {
  6. this._state = { ...initialState };
  7. this._listeners = [];
  8. }
  9. subscribe(listener: (state: T) => () => void) {
  10. this._listeners.push(listener);
  11. const unsubscribe = () => {
  12. const index = this._listeners.indexOf(listener);
  13. if (index > -1) {
  14. this._listeners.splice(index, 1);
  15. }
  16. };
  17. return unsubscribe;
  18. }
  19. setState(state: T) {
  20. Object.assign(this._state, { ...state });
  21. for (const listener of this._listeners) {
  22. if (typeof listener === 'function') {
  23. listener(this._state);
  24. }
  25. }
  26. }
  27. getState() {
  28. return this._state;
  29. }
  30. }
  31. export default Store;