JavaScript Proxy, Reflect and reactive story

Tram Ho


Suppose we have the formula for calculating the total amount based on the quantity and price of a product as follows:

If we change the price of the product

Now total still 10. Because that’s how javascript works.

So is there any way to make the value of this total reactive . That is, will its value change based on price and quantity ? Let’s continue to read the article ❤️

The answer

I will put the total calculation above in a function and call it a effect

Thus, to solve the above problem, we will find a way to run this effect function whenever price and quantity change.

And to do that, we will define price and quantity in an object . Type as follows:

And our effect will become

Next we will loop through each property in the state object and use Object.defineProperty to redefine the getter and setter for the state as follows:

Thus, when we assign the value state.price = 10 for example, it will run the effect function.

And so the total is updated!

Furthermore, we can create a function that can be reused for other objects as follows:

And our state will look like this:

OK, delicious.

Wait wait. Why haven’t you said anything about Proxy ?

Here!. With Proxy we can redefine reactive function in a more concise way:

And if using Reflect :

Now if we initialize the state with reactive , we will get a Proxy as follows:

OK, genuine.

Actually, Proxy not only makes our code more concise, but also helps in dealing with reactive arrays, …

In this article, I just introduced a brief overview of reactive . We can see that the actual effect must also be saved and calculated in some way so that we can use multiple effect at the same time.

The article came here, I don’t really understand it. You can find out more carefully in the link below. Good luck ❤️


Share the news now

Source : Viblo