Created
October 16, 2023 02:31
-
-
Save anjanesh/757c7e763653ac8be6b923b39f4a5d0f to your computer and use it in GitHub Desktop.
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> | |
<head> | |
<meta charset="utf-8" /> | |
<meta name="viewport" content="width=device-width, initial-scale=1" /> | |
<title>AlpineJS auto update of another variable on variable change</title> | |
</head> | |
<body> | |
<script> | |
// Using Vanilla JavaScript | |
let product = { | |
price_INR: 83, | |
set price_USD(val) | |
{ | |
this.price_INR = val * 83; | |
}, | |
get price_USD() | |
{ | |
return this.price_INR / 83; | |
} | |
}; | |
document.addEventListener("DOMContentLoaded", () => | |
{ | |
console.log('product in USD = ', product.price_USD); | |
console.log('product in INR = ', product.price_INR); | |
product.price_USD = 50; | |
console.log('product in USD = ', product.price_USD); | |
console.log('product in INR = ', product.price_INR); | |
}); | |
// Using AlpineJS's store object | |
document.addEventListener('alpine:init', () => | |
{ | |
Alpine.store('global_data', | |
{ | |
price_INR: 83, | |
set price_USD(val) | |
{ | |
this.price_INR = val * 83; | |
}, | |
get price_USD() | |
{ | |
return this.price_INR / 83; | |
} | |
}); | |
}); | |
document.addEventListener("DOMContentLoaded", () => | |
{ | |
console.log('price_USD = ', Alpine.store('global_data').price_USD); | |
console.log('price_INR = ', Alpine.store('global_data').price_INR); | |
Alpine.store('global_data').price_USD = 50; | |
console.log('price_USD = ', Alpine.store('global_data').price_USD); | |
console.log('price_INR = ', Alpine.store('global_data').price_INR); | |
}); | |
</script> | |
<div x-data=""> | |
Right click on the page and Inspect > Open Console | |
</div> | |
<script defer src="https://unpkg.com/[email protected]/dist/cdn.min.js"></script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment