Property changed event on Javascript objects.

Recently I ran across a question on StackOverflow.com. The question was: “Is it possible to have an event that fires when the value of a certain variable changes“. My first reaction was “No… you can’t”. You must create a setter method on your object and pray that the users of your code use the setter method instead of setting the variable itself.

But luckily there are people in this world who are more ingenious than me… it is possible. You must write a little bit of code on the Object-prototype but it is quite self explaining. The code is found here: Eli Grey’s Gist.

I copy/pasted the code here below (changed some formatting). But again… All credits go to Eli Grey.

// object.watch
if (!Object.prototype.watch)
{
    Object.prototype.watch = function (prop, handler)
    {
        var val = this[prop],
        getter = function ()
        {
            return val;
        },
        setter = function (newval) {
            return val = handler.call(this, prop, val, newval);
        };
        if (delete this[prop]) { // can't watch constants
            if (Object.defineProperty) { // ECMAScript 5
                Object.defineProperty(this, prop, {
                   get: getter,
                   set: setter
                });
            }
            else if (Object.prototype.__defineGetter__ &&
                     Object.prototype.__defineSetter__) //legacy
            {
                Object.prototype.__defineGetter__.call(this, prop, getter);
                Object.prototype.__defineSetter__.call(this, prop, setter);
            }
        }
    };
}

// object.unwatch
if (!Object.prototype.unwatch)
{
    Object.prototype.unwatch = function (prop) {
        var val = this[prop];
        delete this[prop]; // remove accessors
        this[prop] = val;
    };
}

That’s it… works great…

Happy Coding…

    • Martin
    • September 14th, 2013

    Thank you for sharing!
    Would you kindly give an example using the above functions?

    • VP as initials
    • July 10th, 2015

    This is bullshit!

    • VP as initials
    • July 10th, 2015

    var _name = “”;
    var vm = {
    set name(v) {
    alert(‘s’);
    }
    };

    …. where the _name is a private variable …. have a nice day with the INotifyProperty changed in the future ;)

  1. No trackbacks yet.