ant-design/components/table/createStore.tsx

40 lines
758 B
TypeScript
Raw Normal View History

export interface Store {
setState: (partial: object) => void;
getState: () => any;
subscribe: (listener: () => void) => () => void;
}
2017-11-21 13:48:37 +08:00
export default function createStore(initialState: object): Store {
let state = initialState;
const listeners: any[] = [];
2017-11-21 13:48:37 +08:00
function setState(partial: object) {
state = {
...state,
...partial,
};
for (let i = 0; i < listeners.length; i++) {
listeners[i]();
}
}
function getState() {
return state;
}
2017-11-21 13:48:37 +08:00
function subscribe(listener: () => any) {
listeners.push(listener);
return function unsubscribe() {
const index = listeners.indexOf(listener);
listeners.splice(index, 1);
};
}
return {
setState,
getState,
subscribe,
};
}