Is it possible to have an event in JS that fires when the value of a certain variable changes? JQuery is accepted.
Recently found myself with the same issue. Wanted to listen for on change of a variable and do some stuff when the variable changed.
Someone suggested a simple solution of setting the value using a setter.
Declaring a simple object that keeps the value of my variable here:
var variableObject = {
value: false,
set: function (value) {
this.value = value;
this.getOnChange();
}
}
The object contains a set method via which I can change the value. But it also calls a getOnChange()
method in there. Will define it now.
variableObject.getOnChange = function() {
if(this.value) {
// do some stuff
}
}
Now whenever I do variableObject.set(true)
, the getOnChange
method fires, and if the value was set as desired (in my case: true
), the if block also executes.
This is the simplest way I found to do this stuff.