Skip to content

Instantly share code, notes, and snippets.

@anjanesh
Created December 11, 2023 02:35
Show Gist options
  • Save anjanesh/18630fc3f7b1684569fc6ad34c45a883 to your computer and use it in GitHub Desktop.
Save anjanesh/18630fc3f7b1684569fc6ad34c45a883 to your computer and use it in GitHub Desktop.
alpine auto update variable method 2
<!DOCTYPE html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>AlpineJS auto update of variable values Method 2</title>
</head>
<body>
<script>
document.addEventListener('alpine:init', () =>
{
Alpine.store('global_data',
{
products:
[
{
name: 'batmobile',
price_USD: 20,
// price_INR: 1660, // 20 x 83
},
{
name: 'herbie',
price_USD: 35,
// price_INR: 2905, // 35 x 83
},
{
name: 'delorean',
price_USD: 51,
// price_INR: 4233, // 51 x 83
},
],
init()
{
const INRPriceConverter =
{
set(val)
{
this.price_USD = val / 83;
},
get()
{
return this.price_USD * 83;
}
}
const addINRPrice = (product) => Object.defineProperty(product, 'price_INR', INRPriceConverter);
this.products.map(addINRPrice);
},
});
});
</script>
<div x-data="">
<template x-for="(product, index) in $store.global_data.products">
<div>
<span x-text="product.name"></span> :
<input x-model="product.price_USD" />
USD =
<input x-model="product.price_INR" /> INR
</div>
</template>
</div>
<script defer src="https://unpkg.com/alpinejs@3.12.3/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