Created
July 23, 2018 22:12
-
-
Save kristoferjoseph/9f6a8a5f88a30f12c8aaa4f5cfaec3e4 to your computer and use it in GitHub Desktop.
Possible store implementation using Proxy.
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 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