See what the variable is on a variable change with js?

- 1 answer

Ad

I have a variable I will call x and I want to see what the variable is when it changes.

Incomplete demo:

var x = 0;
x = 1;

whenxchanges = {
    if (x == 0){
        alert(x);
    }
    else {
        alert(x);
    }
}

Demo is just showing what I want to happen.

Thanks!

Please no Jquery

Ad

Answer

Ad

In a browser like Chrome or Firefox (firebug) you could run the program step by step, inspect the value, etc...

Besides, you cannot force Javascript to trigger an event when x changes.


However you could make a function (setx), having x global, or having setx a nested function within a function where x is defined:

function setx(v) {
    alert("x changes!");
    x = v;
}

Then instead of doing

x = 7;

you do

setx(7);

and the alert is triggered. Replace all x assignments with a call to setx and you'll be notified whenever x changes, ie whenever setx is called.

This is of course basic cross-browser JS.

Ad
source: stackoverflow.com
Ad