Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I attach a change event handler to a variable? [duplicate]

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?

like image 353
Travis J Avatar asked Jul 30 '12 21:07

Travis J


People also ask

What is the best way to attach an event handler to an object?

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 ).

Which method attaches an event handler to an element?

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.

Which operator is used to attach an event handler to an event?

Use the addition assignment operator ( += ) to attach an event handler to the event.


2 Answers

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; }
});
like image 95
2 revs, 2 users 86%user1106925 Avatar answered Oct 01 '22 19:10

2 revs, 2 users 86%user1106925


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.

like image 26
Rocket Hazmat Avatar answered Oct 01 '22 19:10

Rocket Hazmat