Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. To put this more into context I have a function which handles the html rendering of an array of objects, and I want that function to be called automatically every time the array is modified.

Thanks.

like image 289
VerizonW Avatar asked Mar 12 '11 12:03

VerizonW


2 Answers

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.

like image 142
pimvdb Avatar answered Sep 24 '22 05:09

pimvdb


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.

like image 39
Pascal MARTIN Avatar answered Sep 22 '22 05:09

Pascal MARTIN