Skip to content

Instantly share code, notes, and snippets.

@anjanesh
Created October 16, 2023 02:31
Show Gist options
  • Save anjanesh/757c7e763653ac8be6b923b39f4a5d0f to your computer and use it in GitHub Desktop.
Save anjanesh/757c7e763653ac8be6b923b39f4a5d0f to your computer and use it in GitHub Desktop.
<!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 &gt; 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