Store.ts 844 B

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