Skip to content

Instantly share code, notes, and snippets.

@myobie
Last active April 14, 2020 08:21
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 myobie/6d3d8167afc8413904dc0594db432b25 to your computer and use it in GitHub Desktop.
Save myobie/6d3d8167afc8413904dc0594db432b25 to your computer and use it in GitHub Desktop.
Very simple state class with an update callback
/** @template T */
class State {
/** @typedef {function(T):void} Callback */
/**
* @param {T} initialValue
*/
constructor (initialValue) {
this.value = initialValue
/** @type Callback[] */
this.callbacks = []
}
/**
* @param {T} newValue
*/
update (newValue) {
this.value = newValue
this.callbacks.forEach(cb => {
cb(this.value)
})
}
/**
* @param {Callback} cb
* @returns {void}
*/
onUpdate (cb) {
this.callbacks.push(cb)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment