Skip to content

Instantly share code, notes, and snippets.

@kristoferjoseph
Created July 23, 2018 22:12
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kristoferjoseph/9f6a8a5f88a30f12c8aaa4f5cfaec3e4 to your computer and use it in GitHub Desktop.
Save kristoferjoseph/9f6a8a5f88a30f12c8aaa4f5cfaec3e4 to your computer and use it in GitHub Desktop.
Possible store implementation using Proxy.
const state = {}
const listeners = []
let aid
const handler = {
set: function setter (obj, prop, value) {
let old = obj[prop]
if (old !== value) {
obj[prop] = value
if (aid) {
window.cancelAnimationFrame(aid)
}
aid = window.requestAnimationFrame(notify)
}
return true
}
}
let actual = new Proxy(state, handler)
function subscribe (l) {
listeners.push(l)
}
function unsubscribe (l) {
listeners.splice(listeners.indexOf(l), 1)
}
function notify () {
let i = 0
let l = listeners.length
let fn
for (i; i < l; i++) {
fn = listeners[i]
fn(state)
}
}
function Store (initialState) {
if (initialState) {
for (let prop in initialState) {
state[prop] = initialState[prop]
}
}
return actual
}
actual.subscribe = subscribe
actual.unsubscribe = unsubscribe
module.exports = Store
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment