Last active
March 8, 2023 08:24
-
-
Save donbrae/ba4bde4d6cf30865178721c3bfaf7ec6 to your computer and use it in GitHub Desktop.
Reactive UI with Proxy object
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!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