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 for changes to a variable? therefore, when its value changes, the event is fired, and then I can call the function. To add this to the context, I have a function that processes the html rendering of an array of objects, and I want this function to be called automatically every time the array changes.

Thanks.

+6
javascript function variables
source share
5 answers

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

+7
source share

I do not think you ask, perhaps.

The solution could be:

  • encapsulate your data in a specific object
  • access to this data using the setter method of this object
  • have this setter method:
    • set data
    • calling your function

But you will need to rewrite some of your code.

+6
source share

ECMAScript 5 has 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 will have to wait for IE9 or use only getters / seters DOM databases.

+2
source share

You can use setInterval to check its value so many times per second and store it in a separate variable. You can check each time whether a real variable is different from another. In this case, call the function.

This is a dirty trick, though.

+1
source share

Since JavaScript does not yet support setter / getter methods, I would recommend that you think about how you set your variables. One of the working methods:

 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 personally am not a big fan of adding new prototyping methods, but in the near future it will simplify refactoring.

+1
source share

All Articles