Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import deepEqual from "fast-deep-equal";
- const debug = true;
- class AppStore {
- constructor(initialState = {}) {
- this.handlers = [];
- this.state = initialState;
- if (debug) {
- console.log("=== store init ===");
- console.log(this.state);
- }
- }
- set(newState = {}) {
- const oldState = this.state;
- let isEqual = true;
- // merge state
- this.state = {
- ...oldState,
- ...newState
- };
- // deep diff
- Object.keys(this.state).forEach(key => {
- if (!oldState.hasOwnProperty(key)) {
- isEqual = false;
- this.fire(key);
- }
- if (!deepEqual(oldState[key], this.state[key])) {
- isEqual = false;
- this.fire(key, oldState[key]);
- }
- });
- !isEqual && this.fire("*", oldState);
- }
- fire(key = "*", oldValue = null) {
- debug && console.log(`=== fire: ${key} ===`);
- // filter handlers
- const handlers = this.handlers.filter(function(item) {
- if (item.key === key) {
- return item;
- }
- });
- const newValue = key === "*" ? this.state : this.state[key];
- // loop through handlers and call functions
- handlers.length &&
- handlers.forEach(handler => {
- handler.fn(oldValue, newValue);
- });
- }
- get(key = "*") {
- return key === "*" ? this.state : this.state[key];
- }
- subscribe(key = "*", fn) {
- this.handlers.push({ key, fn });
- }
- unsubscribe(fn) {
- this.handlers = this.handlers.filter(function(item) {
- if (item.fn !== fn) {
- return item;
- }
- });
- }
- }
- const store = new AppStore({
- loading: true,
- transitionState: null
- });
- export default store;
- /* TEST */
- setTimeout(() => {
- store.set({ loading: true, foo: "bar" });
- }, 1000);
- setTimeout(() => {
- store.set({ loading: false });
- }, 2000);
- setTimeout(() => {
- /* should not do anything */
- store.set({ loading: false });
- }, 3000);
- setTimeout(() => {
- store.set({ foo: "foo" });
- }, 4000);
- setTimeout(() => {
- console.log(store.get());
- }, 5000);
- setTimeout(() => {
- console.log(store.get("loading"));
- }, 6000);
- store.subscribe("loading", (oldValue, newValue) => {
- console.log("Subscribed to: loading");
- console.log({ oldValue, newValue });
- });
- store.subscribe("*", (oldValue, newValue) => {
- console.log("Subscribed to: * (everything)");
- console.log({ oldValue, newValue });
- });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement