Is it possible (using jQuery or otherwise) to listen for a change in the value of a non-DOM Javascript object (or variable)?
So, for instance, I have:
function MyObject(){
this.myVar = 0;
}
var myObject = new MyObject();
myObject.myVar = 100;
Is there a way to listen for when the value of myVar changes and call a function?
I know that I could use getter/setters, but they aren't supported in previous versions of IE.
Basically you have two options
watch method which is available only in FirefoxThe third and cross-platform option is to use polling which is not so great
Example of watch
var myObject = new MyObject();
// Works only in Firefox
// Define *watch* for the property
myObject.watch("myVar", function(id, oldval, newval){
alert("New value: "+newval);
});
myObject.myVar = 100; // should call the alert from *watch*
Example of getters and setters
function MyObject(){
// use cache variable for the actual value
this._myVar = undefined;
}
// define setter and getter methods for the property name
Object.defineProperty(MyObject.prototype, "myVar",{
set: function(val){
// save the value to the cache variable
this._myVar = val;
// run_listener_function_here()
alert("New value: " + val);
},
get: function(){
// return value from the cache variable
return this._myVar;
}
});
var m = new MyObject();
m.myVar = 123; // should call the alert from *setter*
If IE is important, I guess you are not interested in Watch
But someone seems to have written a shim which makes this question a duplicate
Watch for object properties changes in JavaScript
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With