/* * Copyright (C) Sapphirecode - All Rights Reserved * This file is part of Modelling which is released under MIT. * See file 'LICENSE' for full license details. * Created by Timo Hocker , May 2020 */ import { Persistent } from './Persistent'; import { PersistentType, ControlObserver, Observer } from './Types'; export abstract class ControlModel extends Persistent { private _before_change: Record = {}; private _observers: Record = {}; public constructor (obj?: Record) { super (); this.define_properties (); if (typeof obj !== 'undefined') this.assign_object (obj); } public set (key: string, value: PersistentType): void { const prev = this.get (key); if (typeof this._before_change[key] !== 'undefined') { for (const obs of this._before_change[key]) { if (!obs (value, prev, key)) return; } } super.set (key, value); if (typeof this._observers[key] !== 'undefined') { for (const obs of this._observers[key]) obs (value, prev, key); } } public before_change (key: string, func: ControlObserver): void { if (typeof this._before_change[key] === 'undefined') this._before_change[key] = []; this._before_change[key].push (func); } public register_observer (key: string, func: Observer): void { if (typeof this._observers[key] === 'undefined') this._observers[key] = []; this._observers[key].push (func); } protected abstract define_properties(): void; }