Skip to content

Instantly share code, notes, and snippets.

@Ivannnnn
Created May 12, 2020 17:32
Show Gist options
  • Save Ivannnnn/8ee1f3cfcb4f85eaaf6b71dde309a456 to your computer and use it in GitHub Desktop.
Save Ivannnnn/8ee1f3cfcb4f85eaaf6b71dde309a456 to your computer and use it in GitHub Desktop.
const audioPlayer = (function () {
const [state, updateState, watchState] = useState({
name: 'Ivan',
})
watchState({
name: (name) => {
console.log('name updated to: ' + name)
},
})
return {
state,
}
})()
const useState = (state = {}) => {
const watchers = {}
const update = (fresh) => {
for (let key in fresh) {
if (state[key] !== fresh[key]) {
state[key] = fresh[key]
watchers[key] && watchers[key].forEach((f) => f(fresh[key]))
}
}
}
const watch = (watchersObj) => {
for (let prop in watchersObj) {
watchers[prop]
? watchers[prop].push(watchersObj[prop])
: (watchers[prop] = [watchersObj[prop]])
}
}
return [state, update, watch]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment