javascriptbrowserdom-events

Listener for property value changes in a Javascript object


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 use watch() and unwatch()! These two methods were implemented only in Firefox prior to version 58, they're deprecated and removed in Firefox 58+


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?


Solution

  • What watch is really designed for is validation of property values. For example you could validate that something is an integer:

    obj.watch('count', function(id, oldval, newval) {
        var val = parseInt(newval, 10);
        if(isNaN(val)) return oldval;
        return val;
    });
    

    You could use it to validate string length:

    obj.watch('name', function(id, oldval, newval) {
        return newval.substr(0, 20);
    });
    

    However, these are only available in the latest versions of the SpiderMonkey javascript engine. Great if you are using Jaxer or embedding the SpiderMonkey engine, but not really available in your browser yet (unless you are using FF3).