Reactive UI with JavaScript Proxy: Simple Example
24 views
Using JavaScript's Proxy object, you can create a reactive UI that updates automatically when certain data changes. Below is a simple example to demonstrate how you can achieve this using HTML and JavaScript.
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Reactive UI with Proxy</title>
</head>
<body>
<div id="app">
<p id="text1">Message: <span id="message">{{ message }}</span></p>
<p id="text2">Counter: <span id="counter">{{ counter }}</span></p>
<button onclick="incrementCounter()">Increment Counter</button>
<button onclick="changeMessage()">Change Message</button>
</div>
<script src="app.js"></script>
</body>
</html>
JavaScript (app.js)
// Initial data
const state = {
message: "Hello, World!",
counter: 0
};
// Select elements that need to be updated
const messageElement = document.getElementById("message");
const counterElement = document.getElementById("counter");
// Define a handler for the Proxy
const handler = {
set(target, property, value) {
target[property] = value;
render(property, value);
return true;
}
};
// Create a Proxy for the state object
const proxyState = new Proxy(state, handler);
// Render function to update the DOM elements
function render(property, value) {
if (property === 'message') {
messageElement.textContent = value;
}
if (property === 'counter') {
counterElement.textContent = value;
}
}
// Functions to change the state
function incrementCounter() {
proxyState.counter += 1;
}
function changeMessage() {
proxyState.message = "You have changed the message!";
}
// Initial render
render('message', proxyState.message);
render('counter', proxyState.counter);
Explanation
- HTML:
- The HTML contains two paragraphs and two buttons. Each paragraph has a span where the reactive data will be displayed.
- JavaScript:
- The
stateobject holds the initial data. messageElementandcounterElementare references to the parts of the DOM that need to be updated.- The
handlerobject defines asetfunction to handle changes to theProxyobject. When a property on theProxyis set, thesetfunction will update the corresponding DOM element by calling therenderfunction. - A
Proxyobject (proxyState) is created to wrap thestateobject, using thehandler. - The
renderfunction updates the DOM elements based on the property that changed. - The
incrementCounterandchangeMessagefunctions update theProxyobject, triggering the UI re-render. - Initial calls to the
renderfunction set the initial state in the DOM.
- The
Usage
- When you click the "Increment Counter" button, the counter is incremented, and the
counterspan is updated. - When you click the "Change Message" button, the message is changed, and the
messagespan is updated.
This setup ensures that DOM elements are automatically updated when the respective data changes, providing a simple reactive UI.