Con la ayuda de getter y setter , puede definir una clase de JavaScript que haga tal cosa.
Primero, definimos nuestra clase llamada MonitoredVariable:
class MonitoredVariable {
constructor(initialValue) {
this._innerValue = initialValue;
this.beforeSet = (newValue, oldValue) => {};
this.beforeChange = (newValue, oldValue) => {};
this.afterChange = (newValue, oldValue) => {};
this.afterSet = (newValue, oldValue) => {};
}
set val(newValue) {
const oldValue = this._innerValue;
// newValue, oldValue may be the same
this.beforeSet(newValue, oldValue);
if (oldValue !== newValue) {
this.beforeChange(newValue, oldValue);
this._innerValue = newValue;
this.afterChange(newValue, oldValue);
}
// newValue, oldValue may be the same
this.afterSet(newValue, oldValue);
}
get val() {
return this._innerValue;
}
}
Supongamos que queremos escuchar los moneycambios, creemos una instancia MonitoredVariablecon dinero inicial 0:
const money = new MonitoredVariable(0);
Entonces podríamos obtener o establecer su valor usando money.val:
console.log(money.val); // Get its value
money.val = 2; // Set its value
Como no hemos definido ningún oyente para ello, no sucede nada especial después de los money.valcambios a 2.
Ahora definamos algunos oyentes. Tenemos cuatro oyentes disponibles: beforeSet, beforeChange, afterChange, afterSet. Lo siguiente sucederá secuencialmente cuando use money.val = newValuepara cambiar el valor de la variable:
- money.beforeSet (newValue, oldValue);
- money.beforeChange (newValue, oldValue); (Se omitirá si su valor no cambia)
- money.val = newValue;
- money.afterChange (newValue, oldValue); (Se omitirá si su valor no cambia)
- money.afterSet (newValue, oldValue);
Ahora definimos el afterChangeoyente que se activará solo después de que money.valhaya cambiado (mientras afterSetque se activará incluso si el nuevo valor es el mismo que el anterior):
money.afterChange = (newValue, oldValue) => {
console.log(`Money has been changed from ${oldValue} to ${newValue}`);
};
Ahora establezca un nuevo valor 3y vea qué sucede:
money.val = 3;
Verá lo siguiente en la consola:
Money has been changed from 2 to 3
Para obtener el código completo, consulte https://gist.github.com/yusanshi/65745acd23c8587236c50e54f25731ab .