Initial version

This commit is contained in:
trading_peter 2022-03-12 22:45:49 +01:00
parent 618c488072
commit bb907d9880
5 changed files with 82 additions and 44 deletions

View File

@ -1 +1 @@
# tp-element # tp-store

37
dataStore.js Normal file
View File

@ -0,0 +1,37 @@
/**
@license
Copyright (c) 2022 trading_peter
This program is available under Apache License Version 2.0
*/
const data = new Map();
const instancesPerKey = new Map();
export const DataStore = new class {
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);
}
};

View File

@ -1,18 +1,15 @@
{ {
"name": "@tp/tp-element", "name": "@tp/tp-store",
"version": "0.0.1", "version": "1.0.0",
"description": "", "description": "",
"main": "tp-element.js", "main": "tp-store.js",
"scripts": { "scripts": {
"test": "echo \"Error: no test specified\" && exit 1" "test": "echo \"Error: no test specified\" && exit 1"
}, },
"repository": { "repository": {
"type": "git", "type": "git",
"url": "https://gitea.codeblob.work/tp-elements/tp-element.git" "url": "https://gitea.codeblob.work/tp-stores/tp-store.git"
}, },
"author": "trading_peter", "author": "trading_peter",
"license": "Apache-2.0", "license": "Apache-2.0"
"dependencies": {
"lit": "^2.2.0"
}
} }

39
store.js Normal file
View File

@ -0,0 +1,39 @@
/**
@license
Copyright (c) 2022 trading_peter
This program is available under Apache License Version 2.0
*/
import { DataStore } from './dataStore';
/**
* # Store
*
* A simple key value store.
*/
export const Store = function(superClass) {
return class extends superClass {
_storeSubscribe(keys) {
if (Array.isArray(keys) === false) {
keys = [ keys ];
}
keys.forEach(key => {
let targetProperty;
if (typeof key === 'object') {
targetProperty = key.targetProperty;
key = key.key;
}
DataStore.addInstance(this, key, targetProperty);
});
}
_storeUpdated(key, newValue, targetProperty) {
this[targetProperty || key] = newValue;
}
_storeWrite(key, value) {
DataStore.writeKey(key, value);
}
};
}

View File

@ -1,35 +0,0 @@
/**
@license
Copyright (c) 2022 trading_peter
This program is available under Apache License Version 2.0
*/
import { LitElement, html, css } from 'lit';
class TpElement extends LitElement {
static get styles() {
return [
css`
:host {
display: block;
}
`
];
}
render() {
const { } = this;
return html`
`;
}
static get properties() {
return { };
}
}
window.customElements.define('tp-element', TpElement);