Going through Javascript documentation, I found the following two functions on a Javascript object looks interesting:
.watch
- Watches for a property to be assigned a value and runs a function when that occurs.
.unwatch
- Removes a watchpoint set with the watch method.
UPDATE: Deprecation warning
Do not usewatch()
andunwatch()
! These two methods were implemented only in Firefox prior to version58
, they're deprecated and removed in Firefox58+
Sample usage:
o = { p: 1 };
o.watch("p", function (id,oldval,newval) {
console.log("o." + id + " changed from " + oldval + " to " + newval)
return newval;
});
Whenever we change the property value of "p", this function gets triggered.
o.p = 2; //logs: "o.p changed from 1 to 2"
I am working on Javascript for the past few years and never used these functions.
Can someone please throw some good use cases where these functions will come in handy?