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;
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:


See an example here:

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:

Entradas relacionadas

Deja una respuesta

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