Created
September 3, 2022 00:16
-
-
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.
This file contains 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> | |
<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