Last active
April 14, 2020 08:21
-
-
Save myobie/6d3d8167afc8413904dc0594db432b25 to your computer and use it in GitHub Desktop.
Very simple state class with an update callback
This file contains 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
/** @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