Skip to content

Instantly share code, notes, and snippets.

@MBlore
Created September 3, 2022 00:16
Show Gist options
  • Save MBlore/9b66cc3122eef96f75d09ae6fcfa98fe to your computer and use it in GitHub Desktop.
Save MBlore/9b66cc3122eef96f75d09ae6fcfa98fe to your computer and use it in GitHub Desktop.
Plain JS showing how the Proxy object can be used to intercept logic.
<!DOCTYPE html>
<html>
<body>
<h1 id="cnt">0</h1>
<script type="text/javascript">
const state = {
count: 0
}
const handler = {
set(obj, prop, newval) {
if (prop === "count") {
document.getElementById("cnt").innerText = newval;
obj[prop] = newval;
}
}
};
const proxyState = new Proxy(state, handler);
setInterval(function() {
// This is the only code running every second, but the view is updating! :O
proxyState.count += 1;
}, 1000);
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment