Posts

Showing posts from December, 2011

Listen a property for changes in JavaScript

There are two very interesting functions of Object in JavaScript - watch and unwatch. These two methods could be used to track changes of some specific properties of any Object. watch() watches for a property of an Object, if a value is assigned to that property, it will run registered function. Example,             Here i have an Object obj1 which has property myprop with value 1. Later watch method is used to register myprop property, if any changes/assignment is made to that property appropriate function is called. In this case whenever myprop of obj1 is assigned a value function is executed and alerts a msg. obj1 = {myprop:1}; //  start watch on obj1.myprop from here obj1.watch("myprop",    function (prop_name, oldval, newval) {       alert("obj1." + prop_name + " changed from " + oldval + " to " + newval)       return newval;    }); // assign new values obj1.myprop = 2; obj1.myprop = 3; obj1.myprop = 4; // unwa