2

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

arodebaugh
  • 468
  • 1
  • 6
  • 26
  • There is no event "simple" solution when a variable changes. – epascarello Dec 17 '15 at 00:59
  • Well they are not the answers I want. I want a very simple version like in the demo – arodebaugh Dec 17 '15 at 01:00
  • [This](https://gist.github.com/eligrey/384583) might be what you want. But, there is no standard Event to test for variable changes. Usually you test for variable changes on a specific JavaScript Event. – StackSlave Dec 17 '15 at 01:18
  • Read the warning at the top of the page first, though. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/watch#Examples – Alberto Rivera Dec 17 '15 at 01:51

1 Answers1

1

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.

Breaking not so bad
  • 26,037
  • 5
  • 67
  • 96