Listening for variable changes in JavaScript (Detectar cambios en variable)

You can define an object like this, in which aInternal represents the field a:

x = {
aInternal: 10,
aListener: function(val) {},
set a(val) {
this.aInternal = val;
this.aListener(val);
},
get a() {
return this.aInternal;
},
registerListener: function(listener) {
this.aListener = listener;
}
}

Then you can register a listener using the following:

x.registerListener(function(val) {
alert(«Someone changed the value of x.a to » + val);
});

So whenever anything changes the value of x.a, the listener function will be fired. Running the following line will bring the alert popup:

x.a=42;

See an example here: https://jsfiddle.net/5o1wf1bn/1/

You can also user an array of listeners instead of a single listener slot, but I wanted to give you the simplest possible example.

 

Post Original: https://stackoverflow.com/questions/1759987/listening-for-variable-changes-in-javascript

Entradas relacionadas

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *