modelling/lib/ControlModel.ts

52 lines
1.6 KiB
TypeScript
Raw Permalink Normal View History

2020-05-02 19:40:53 +02:00
/*
* 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 <timo@scode.ovh>, May 2020
*/
2020-05-05 11:37:48 +02:00
import { Persistent } from './Persistent';
2020-06-06 15:48:43 +02:00
import { PersistentType, ControlObserver, Observer } from './Types';
2020-05-02 21:11:55 +02:00
2020-05-05 11:37:48 +02:00
export abstract class ControlModel extends Persistent {
2020-06-06 15:48:43 +02:00
private _before_change: Record<string, ControlObserver[]> = {};
private _observers: Record<string, Observer[]> = {};
public constructor (obj?: Record<string, PersistentType>) {
2020-05-04 20:04:38 +02:00
super ();
2020-05-05 11:48:46 +02:00
this.define_properties ();
2020-05-05 11:37:48 +02:00
if (typeof obj !== 'undefined')
this.assign_object (obj);
2020-05-02 21:18:32 +02:00
}
2020-06-06 15:48:43 +02:00
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;
}
}
2020-05-04 20:13:41 +02:00
2020-06-06 15:48:43 +02:00
super.set (key, value);
if (typeof this._observers[key] !== 'undefined') {
for (const obs of this._observers[key])
obs (value, prev, key);
}
2020-05-02 21:11:55 +02:00
}
2020-06-06 15:48:43 +02:00
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);
2020-05-02 21:11:55 +02:00
}
2020-04-23 17:09:14 +02:00
2020-06-06 15:48:43 +02:00
public register_observer (key: string, func: Observer): void {
if (typeof this._observers[key] === 'undefined')
this._observers[key] = [];
this._observers[key].push (func);
2020-04-23 17:09:14 +02:00
}
2020-05-05 11:48:46 +02:00
protected abstract define_properties(): void;
2020-04-23 17:09:14 +02:00
}