Created
December 3, 2018 16:14
-
-
Save yukeehan/bdc9d20b38f75e310fe320054418c902 to your computer and use it in GitHub Desktop.
creatStore from Scratch
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const createStore = (reducer) => { | |
let state; | |
let listeners = []; // an array of listeners | |
const getState = () => state; | |
const dispatch = (action) => { | |
state = reducer(state, action); | |
listeners.forEach(listener => listener()); // to notify every change listener by calling it | |
}; | |
const subscribe = (listener) => { | |
listeners.push(listener); | |
return () => { | |
listeners = listeners.filter (l => l !== listener); // unsubscribe the listener that alredy been fired | |
}; | |
}; | |
dispatch({}); // initial state populated dummy action | |
return { getState, dispatch, subscribe }; // 3 main methods of createStore | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment