Created
July 19, 2018 23:44
-
-
Save kristoferjoseph/d6db9a78a99a1e638bb47c9bdeb25f5f to your computer and use it in GitHub Desktop.
Tried to make the simplest store module I could muster. Works pretty well.
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
var listeners = [] | |
var state = {} | |
var noop = x => x | |
function subscribe (fn) { | |
listeners.push(fn) | |
} | |
function unsubscribe (fn) { | |
listeners.splice(listeners.indexOf(fn), 1) | |
} | |
function dispatch (action) { | |
action = action || noop | |
let l = listeners.length | |
let fn | |
state = action(state) || state | |
for (let i = 0; i < l; i++) { | |
fn = listeners[i] | |
fn(state) | |
} | |
} | |
function store (initialState) { | |
if (initialState) { | |
state = Object.assign(state, initialState) | |
} | |
return state | |
} | |
store.subscribe = subscribe | |
store.unsubscribe = unsubscribe | |
store.dispatch = dispatch | |
export default store |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment