Reactive state in vanilla JS
Simple test playing with Proxy and Reactive state in vanilla JS
Its just so simple
HTML
<section class="container" id="app">
<h1>Type in input!</h1>
<input type="text" onkeyup="state.tjo = this.value">
<blockquote data-text="tjo"></blockquote>
</section>
JAVASCRIPT
const Observer = (target, listener) => {
return new Proxy(target, {
set: (obj, key, value) => {
listener(obj);
return Reflect.set(obj, key, value)
},
get: (obj, key) => {
return Reflect.get(obj, key)
}
});
};
const state = Observer(
{
hello: "World",
tjo: "test"
},
(state) => {
Array.from(document.querySelectorAll("[data-text]")).map((el) => {
el.innerText = state[el.dataset.text];
});
}
);
Live example at https://codepen.io/hugosp/pen/LYNrpWv?editors=1011