JSFiddle - React, Tailwind, and code Playground
by Pankaj Kargirwar
HTML
<div id="app">
<button id="incrementBtn">
Inc
</button>
</div>
JavaScript
class UIComponent {
constructor() {
this.data = {
counter: 0,
};
this.handler = {
set: (target, property, value) => {
// Intercepting data changes
console.log(`Data change: ${property} = ${value}`);
target[property] = value;
// Update the DOM based on the data change
this.updateDOM();
return true;
},
};
// Create a proxy for the data
this.proxy = new Proxy(this.data, this.handler);
// Initial rendering
this.render();
}
updateDOM() {
// Update the DOM based on the current data
const counterElement = document.getElementById('counter');
counterElement.innerText = this.data.counter;
}
render() {
// Initial rendering
const appContainer = document.getElementById('app');
appContainer.innerHTML = `
<div>
<p>Counter: <span id="counter">${this.data.counter}</span></p>
<button id="incrementBtn">Increment</button>
</div>
`;
// Attach event listener for button click
const incrementBtn = document.getElementById('incrementBtn');
incrementBtn.addEventListener('click', () => {
// Modify the data through the proxy
this.proxy.counter += 1;
});
}
}
// Create an instance of UIComponent
const ui = new UIComponent();