Skip to content
Advertisement

How to subscribe to object changes?

I wonder how to subscribe to the changes of a JavaScript object e.g. like Redux does. I read through a lot of JS documentations but I couldn’t find a non-deprecated way to handle this problem (Object.protype.watch() as well as Object.observe() are deprecated). Moreover I read a few Stackoverflow questions regarding this topic but they are all at least 5 years old. To visualize my problem I’ll show an example.

This could be an object I want to watch for:

JavaScript

.. and this a function which changes the store object:

JavaScript

My goal in this example is to trigger the following function every time the store object changes

JavaScript

Thank you in advance!

Advertisement

Answer

Have you tried using Proxy from ECMA6? I think this is what you are looking for You only have to define a function as the set of the validator of the Proxy like this:

JavaScript
Advertisement