Sunday, March 18, 2007

JavaScript watch function

watch: Watches for a property to be assigned a value and runs a function when that occurs.
Syntax: watch(prop, handler)
Description: Watches for assignment to a property named prop in this object, calling handler(prop, oldval, newval) whenever prop is set and storing the return value in that property. A watchpoint can filter (or nullify) the value assignment, by returning a modified newval (or oldval).

o = {p:1};
o.watch("p",
function (id,oldval,newval) {
document.write("o." + id + " changed from " + oldval + " to " + newval + "
");
return newval;
})

o.p = 2;
o.p = 3;
delete o.p;
o.p = 4;
o.unwatch('p');
o.p = 5;

No comments :