2022-03-12 22:45:49 +01:00
|
|
|
/**
|
|
|
|
@license
|
|
|
|
Copyright (c) 2022 trading_peter
|
|
|
|
This program is available under Apache License Version 2.0
|
|
|
|
*/
|
|
|
|
|
2022-03-12 22:57:00 +01:00
|
|
|
const data = new Map();
|
|
|
|
const instancesPerKey = new Map();
|
2022-03-12 22:45:49 +01:00
|
|
|
|
|
|
|
/**
|
|
|
|
* # Store
|
|
|
|
*
|
|
|
|
* A simple key value store.
|
|
|
|
*/
|
|
|
|
export const Store = function(superClass) {
|
|
|
|
return class extends superClass {
|
2022-03-12 22:57:00 +01:00
|
|
|
storeSubscribe(keys) {
|
2022-03-12 22:45:49 +01:00
|
|
|
if (Array.isArray(keys) === false) {
|
|
|
|
keys = [ keys ];
|
|
|
|
}
|
|
|
|
|
|
|
|
keys.forEach(key => {
|
|
|
|
let targetProperty;
|
|
|
|
if (typeof key === 'object') {
|
|
|
|
targetProperty = key.targetProperty;
|
|
|
|
key = key.key;
|
|
|
|
}
|
2022-03-12 22:57:00 +01:00
|
|
|
this._addInstance(this, key, targetProperty);
|
2022-03-12 22:45:49 +01:00
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2022-03-12 22:57:00 +01:00
|
|
|
storeUpdated(key, newValue, targetProperty) {
|
2022-03-12 22:45:49 +01:00
|
|
|
this[targetProperty || key] = newValue;
|
|
|
|
}
|
|
|
|
|
2022-03-12 22:57:00 +01:00
|
|
|
storeWrite(key, value) {
|
|
|
|
this._writeKey(key, value);
|
|
|
|
}
|
|
|
|
|
|
|
|
_addInstance(instance, key, targetProperty) {
|
|
|
|
if (instancesPerKey.has(key) === false) {
|
|
|
|
instancesPerKey.set(key, [ { instance, targetProperty } ]);
|
|
|
|
} else {
|
|
|
|
instancesPerKey.get(key).push({ instance, targetProperty });
|
|
|
|
}
|
|
|
|
|
|
|
|
if (data.has(key)) {
|
|
|
|
this._notifyInstance(instance, key, data.get(key), targetProperty);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
_writeKey(key, value) {
|
|
|
|
data.set(key, value);
|
|
|
|
|
|
|
|
const instances = instancesPerKey.get(key);
|
|
|
|
if (Array.isArray(instances)) {
|
|
|
|
instances.forEach(entry => {
|
|
|
|
this._notifyInstance(entry.instance, key, value, entry.targetProperty);
|
|
|
|
});
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
_notifyInstance(instance, key, value, targetProperty) {
|
|
|
|
instance._storeUpdated(key, value, targetProperty);
|
2022-03-12 22:45:49 +01:00
|
|
|
}
|
|
|
|
};
|
|
|
|
}
|