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?
The most flexible way to set an event handler on an element is to use the EventTarget. addEventListener method. This approach allows multiple listeners to be assigned to an element, and for listeners to be removed if needed (using EventTarget. removeEventListener ).
The addEventListener() method attaches an event handler to the specified element. The addEventListener() method attaches an event handler to an element without overwriting existing event handlers. You can add many event handlers to one element.
Use the addition assignment operator ( += ) to attach an event handler to the event.
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; }
});
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With