UNPKG

lazy-widgets

Version:

Typescript retained mode GUI for the HTML canvas API

68 lines 1.83 kB
/** * An aggregate helper class for widgets that contain a variable with a * specified type which is intended to be controlled by the user. * * Useful for implementing widgets such as sliders, checkboxes, text input, * etc... * * @typeParam V - The type of {@link Variable#value}. * * @category State Management */ export class Variable { /** * @param initialValue - The initial value of this variable. Sets {@link Variable#_value}. */ constructor(initialValue) { /** The function callbacks called when the value is changed */ this.callbacks = new Array(); this._value = initialValue; } /** * The current value. * * If setting, {@link Variable#setValue} is called with no group. */ get value() { return this._value; } set value(value) { this.setValue(value); } watch(callback, callNow = false, group) { this.callbacks.push(callback); if (callNow) { this.doCallback(callback, group); } return this; } unwatch(callback) { const i = this.callbacks.indexOf(callback); if (i === -1) { console.warn('unwatch called, but watcher was not registered'); } else { this.callbacks.splice(i, 1); } return this; } setValue(value, group) { if (this._value === value) { return false; } this._value = value; for (const callback of this.callbacks) { this.doCallback(callback, group); } return true; } doCallback(callback, group) { try { callback(this, group); } catch (e) { console.error('Exception in watcher:', e); } } } //# sourceMappingURL=Variable.js.map