Track object change

// A simple Javascript Object / String var object = "hello"; // Imagine a button in the DOM, and if it clicked the object value will change document.getElementById("button").onclick = function(){ window.object = "hello world"; } // Now I would like to track and do something when the object is changed, ex: object.onreadystatechange = function(){ alert(object); } 

Note. This may seem silly because I can get the change in the onclick event on the button, but this is not what I want, I want to strictly track the change in the object itself for any kind of use, the above code is just an example.

+6
source share
5 answers

Well, you can make this an actual oject using the get and set methods:

 // A simple Javascript Object var object = new (function(){ this.text = 'hello'; this.setText = function(msg){ this.text = msg //on change event } })(); // Imagine a button in the DOM, and if it clicked the object value will change document.getElementById("button").onclick = function(){ object.setText('New Text'); } 

Here is a demo script: http://jsfiddle.net/maniator/BSYpz/

+5
source

Javascript does not allow you to set software watchpoints / events on arbitrary objects / variables.

You can use encapsulation to hide individual values โ€‹โ€‹inside an object from the outside world, which allows them to be changed only with the help of special "setter" functions that have the desired side effects.

+6
source

You can track the JavaScript object using Getters and Setters, as described here,

http://ejohn.org/blog/javascript-getters-and-setters/

You can also see

Javascript recipients and setters for layouts?

+4
source

No matter what infrastructure you want to use, there is no magic to automatically trigger an event when a property changes. In your situation, what you should do is probably causing the object to surround this data and expose only the get and set methods for it:

 var something = function() { var value = 10; this.getValue = function() { return value; } this.setValue = function(newValue) { ValueChanging(value, newValue); value = newValue; } var ValueChanging = function(old, new) { // Do Something } } 
+3
source

Recent versions of Google Chrome (for example, with the "Enable experimental JavaScript" flag) support the Object.observe () API. More information on RESPONDING TO THE IMAGE WITH OBJECT.OBSERVE and a working example

+3
source

Source: https://habr.com/ru/post/887736/


All Articles