0

Possible Duplicate:
detect variable change in javascript

How can i found out that my variable has changed?

I have an event that performed every time when my variable is for example == 1, i want it to perfome only when my variable changes.

Community
  • 1
  • 1
TRAVA
  • 211
  • 2
  • 12

5 Answers5

2

You can do that via a property setter, which is a newly-standardized part of the language (new as of the ECMAScript5 specification). That will only work for a property defined with a setter on an object, not with any old variable or property.

Here's an example of an object with a foo property with both a getter and a setter:

var obj = {};
Object.defineProperty(obj, "foo", (function(){
  var value = 42;

  function fooGet() {
    display("Getting: " + value);
    return value;
  }
  function fooSet(newValue) {
    display("Setting: " + newValue);
    value = newValue;
  }

  return {
    get: fooGet,
    set: fooSet
  };
})());

Live example, but only works on browsers with support for ECMAScript5 properties, which I think is just Google Chrome at the moment

Or of course, just directly use getter and setter functions rather than properties. :-)

T.J. Crowder
  • 879,024
  • 165
  • 1,615
  • 1,639
2

Simple: Don't use a primitive variable but an object which has a "setter" method to change the value. In the setter, you can call additional code.

Aaron Digulla
  • 297,790
  • 101
  • 558
  • 777
2

You can't do this with primitives. The only way it would be possible is if you encapsulated the variable in an object, and added some custom events to this object.

Skilldrick
  • 65,202
  • 32
  • 168
  • 226
1

You could use the setInterval method to periodically check the variable's value and do your stuff if it's what you want.

It's not a nice solution, though. The other suggestions are better.

http://www.elated.com/articles/javascript-timers-with-settimeout-and-setinterval/

EDIT:

var myVar = 0;

var intervalId = setInterval('checkVariable(myVar);', 3000);

function checkVariable(theVar) {
    if (theVar == 1) {
        alert('Variable is 1.');
    }
}

That will execute checkVariable(myVar) every 3 seconds.

Edgar
  • 4,098
  • 4
  • 38
  • 56
1

@T.J. I think @Aaron is suggesting an object that does something like this:

var myVar = new Watched(1, function (newValue) { alert(newValue) });

myVar.add(2); // alert(3);
myVar.add(10); // alert(13)

Where Watched maintains an internal value that is updated by methods, which fire a callback to say they have updated.

EDITED:

Ok maybe not what @Aaron was thinking:)

I had something very simple like this in mind:

function Watched (initVal, cb) {
    var value = initVal;

    function add (val) {
        value += val;
        cb(value);
    }

    // return public methods
    return { add: add };
}
johnhunter
  • 1,756
  • 14
  • 18