This is going to be a 3 part series on using getters and setters in AlpineJS.
I knew about set and get in JavaScript which are commonly known as setters and getters but I had never used them in a real case scenario until now. I agree, I am pretty late to implementing these, considering these have been available since Chrome 1.0 and Firefox 1.5.
Here is an example of a basic example of using get and set in an AlpineJS global store object.
Let's say you have a product for which you want to show the price in INR (Indian Rupee ₹) and also in US dollars.
Normally we set the price in USD and convert it into INR using a factor of 83 (as of now 1 USD = 83 INR approximately).
So if we set the price of the product as 50 USD, then the price in INR should automatically be converted to 50 x 83 = 4150 INR.
The idea is to set another variable to a converted value when one variable gets changed.
So basically, if we have 2 variables, x
and y
, y
should auto-update when x
gets modified.
This will work only if both x
and y
are defined in an object.
Demo: https://anjanesh.s3.amazonaws.com/demo/alpine/alpine-auto-update-variable.html