apollo-form
Version:
Form state manager
37 lines (36 loc) • 1.15 kB
JavaScript
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const cloneDeep_1 = __importDefault(require("lodash/cloneDeep"));
class Observable {
constructor(value) {
this.listeners = [];
this.watchers = [];
this.timeouts = [];
this.value = cloneDeep_1.default(value);
this.initialValue = cloneDeep_1.default(value);
}
get() {
return this.value;
}
set(val) {
if (this.value !== val) {
const prev = this.value;
this.value = val;
this.listeners.forEach(l => l.event(l.selector ? l.selector(val) : val));
const timeoutId = setTimeout(() => {
this.watchers.forEach(l => l(val, prev));
}, 0);
this.timeouts.push(timeoutId);
}
}
watch(handler) {
this.watchers.push(handler);
return () => {
this.watchers = this.watchers.filter(l => l !== handler);
};
}
}
exports.default = Observable;