Skip to content Skip to sidebar Skip to footer

How To Run A Function In JavaScript Every Time A Variable Changes?

Is there a way in JavaScript to have something like an event that listens to changes in a variable? so when its value is modified the event triggers and then I can call a function.

Solution 1:

Use object.watch and if it is not supported natively look at this implementation: Object.watch() for all browsers?


Solution 2:

I don't think what you ask is possible.

A solution might be to :

  • encapsulate your data into a specific object
  • access that data using a setter method of that object
  • have that setter method both :
    • set the data
    • call your function

But it'll require you to rewrite a bit of your code.


Solution 3:

You could use setInterval to check for its value so many times a second, and save it into a separate variable. You can check each time whether the real variable is different from the other one. In that case, call the function.

It's a dirty trick, though.


Solution 4:

In ECMAScript 5 there are getter/setter properties... Read here: http://ejohn.org/blog/ecmascript-5-objects-and-properties/

Non-IE browsers support something similar:

http://robertnyman.com/2009/05/28/getters-and-setters-with-javascript-code-samples-and-demos/

For IE, you'll have to wait for IE9, or use only DOM-bases getters/setters.


Solution 5:

Because JavaScript doesn't universally support setter/getter methods yet, I'd recommend you think about how you set your variables. One technique that would work is:

Array.prototype.setMember = function(index,newValue) {
    alert("I will perform some action here");
    this[index] = newValue;
}

var myArray = [1,2,3];
// x[0] = 11; // Don't do this any more
x.setMember(0,11);
alert(x[0]);

I'm personally not a huge fan of adding new methods to base prototypes, but it makes things easier to refactor in the short term.


Post a Comment for "How To Run A Function In JavaScript Every Time A Variable Changes?"