Created
March 12, 2024 22:37
-
-
Save joeyklee/c5431adb5dec50028732e9b06937071d to your computer and use it in GitHub Desktop.
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> | |
<meta charset="UTF-8"> | |
<meta name="viewport" content="width=device-width, initial-scale=1.0"> | |
<title>Document</title> | |
</head> | |
<body> | |
<h1 class="title apple-count"></h1> | |
<p>today I ate <span class="apple-count"></span> apples</p> | |
<input class="apple-counter-input" type="text" placeholder="number of apples" value="0"> | |
</body> | |
<script> | |
// https://blog.logrocket.com/practical-use-cases-for-javascript-es6-proxies/ | |
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy/Proxy | |
const $input = document.querySelector('.apple-counter-input') | |
const $appleCountTextList = document.querySelectorAll('.apple-count') | |
const myState = { | |
value: 0, | |
}; | |
const myStateHandler = { | |
set(target, key, value) { | |
if (!value) { | |
$appleCountTextList.forEach(el => { | |
el.textContent = 'no' | |
}) | |
return true; | |
} | |
$appleCountTextList.forEach(el => { | |
el.textContent = $input.value | |
}) | |
return true; | |
}, | |
}; | |
const proxy1 = new Proxy(myState, myStateHandler); | |
proxy1.value = myState.value | |
$input.addEventListener('keyup', (evt) => { | |
proxy1.value = evt.target.value | |
}) | |
</script> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment