Skip to content

Instantly share code, notes, and snippets.

@kristoferjoseph
Created July 19, 2018 23:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kristoferjoseph/d6db9a78a99a1e638bb47c9bdeb25f5f to your computer and use it in GitHub Desktop.
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.
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