10

Possible Duplicate:
Listening for variable changes in JavaScript or jQuery

How can I track if this variable has changed?

var ConditionalFlag = 0;

I tried this:

var ConditionalFlag = 0;
$(ConditionalFlag).change(function () {
    alert("Changed");
});
ConditionalFlag++;

But to no avail. I have considered using a 25ms timer to check for change like this:

var ConditionalFlag = 0;
function CheckFlag() {
    if (ConditionalFlag > 0) {
        alert("Changed");
        clearInterval(check);
    }
}
var check = window.setInterval("CheckFlag()", 25);
ConditionalFlag++;

However, that seems like overkill. Is there a way to attach an event handler to this variable with jQuery or javascript?

Community
  • 1
  • 1
Travis J
  • 77,009
  • 39
  • 185
  • 250

2 Answers2

10

If it's a global variable, you can use property accessors in supported environments...

window._conditional_flag = 0;
Object.defineProperty(window, "ConditionalFlag", {
    get: function() { return window._conditional_flag},
    set: function(v) { console.log("changed"); window._conditional_flag = v; }
});
Rocket Hazmat
  • 204,503
  • 39
  • 283
  • 323
  • 2
    I'm gonna assume this only works on modern web browsers (so not IE). – Rocket Hazmat Jul 30 '12 at 21:17
  • @Rocket: Works in IE9+ only. Older Firefox has the `__setter__` and `__getter__` properties. I believe FF4+ supports the standard accessors. –  Jul 30 '12 at 21:18
  • This is really cool! I haven't messed with `get` and `set` in JavaScript before :-) – Rocket Hazmat Jul 30 '12 at 21:19
  • @Rocket: They are cool, but in my previous testing, they're also slow. I assume/hope they will eventually be optimized. –  Jul 30 '12 at 21:20
5

There's no "event" that gets triggered when a variable changes. JavaScript doesn't work that way.

When does this variable get changed? Just add a call to a function after it does.

Rocket Hazmat
  • 204,503
  • 39
  • 283
  • 323
  • 1
    It gets changed as a result of multiple pieces falling into place. I suppose I could just set the pieces to be changed inside of a function which then calls the next function if all of the pieces are set - kind of like how teeth in a key lineup in a lock. – Travis J Jul 30 '12 at 21:13
  • 1
    @TravisJ: That sounds like a better idea. Personally, I feel that if you are "watching" a variable, you're not doing something quite right. – Rocket Hazmat Jul 30 '12 at 21:14