Skip to content

Instantly share code, notes, and snippets.

@donbrae
Last active March 8, 2023 08:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save donbrae/ba4bde4d6cf30865178721c3bfaf7ec6 to your computer and use it in GitHub Desktop.
Save donbrae/ba4bde4d6cf30865178721c3bfaf7ec6 to your computer and use it in GitHub Desktop.
Reactive UI with Proxy object
<!DOCTYPE html>
<html lang="en">
<head>
<title>Reactive UI with Proxy object</title>
</head>
<body>
<!-- Comment which got me thinking: https://news.ycombinator.com/item?id=35062021 -->
<p>Count:
<span id="count"></span>
</p>
<script>
const appState = {
count: 0
};
const stateHandler = {
get: function (target, property) {
console.log('get', target, property);
return target[property];
},
set: function (target, property, value) {
console.log('set', target, property, value);
target[property] = value;
updateCount();
}
};
const proxiedState = new Proxy(appState, stateHandler);
function updateCount() {
const countElem = document.getElementById('count');
countElem.textContent = proxiedState.count;
}
updateCount(); // Initialize onscreen value with initial state value
</script>
<button onclick="proxiedState.count++;">Increment</button>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment