UNPKG

@mic-rexjs/usecases

Version:
34 lines (33 loc) 807 B
export class EntityStore { #watchers = []; value; constructor(initialEntity, options = {}) { const { onChange } = options; this.value = initialEntity; if (!onChange) { return; } this.watch(onChange); } setValue(value) { const { value: oldValue } = this; this.value = value; if (oldValue === value) { return; } for (const watcher of this.#watchers) { watcher(value, oldValue); } } unwatch(watcher) { const watchers = this.#watchers; const index = watchers.indexOf(watcher); if (index === -1) { return; } watchers.splice(index, 1); } watch(watcher) { this.#watchers.push(watcher); } }