Skip to content

JavaScript trigger event on Value of object Change

How to track change value of object in JavaScript.
First declare one variable as:

var man={val:0};

What if we need to track change value of man.val or say how to trigger code in javascript for changing value of any variable. we can use watch().

man.watch('val', function (id, oldval, newval) {
     /*Here id = man.val, oldval = old value of man.val which is 
     Second parameter in function, newval = assigned value to man.val
    write code here to do for changing value of man.val */
    // as example
    console.log('new value of '+ id+ ' is ' +newval+ ' and old is ' +  oldval);
});

here if we assign value in man.val then console.log work and it printed in console window of browser.
lets run

man.val = 1 

then in console window we get output as

new value of val is 1 and old is 0

By pressing F12 on browser you will get console windows and run above code you will get this.

watch-javascipt-mozila
you can also release watching of variable by unwatch().

man.unwatch('val');

unfortunately watch is only work on Mozilla Firefox browser 🙁

Leave a Reply

%d bloggers like this: