How to run a function in JavaScript every time a variable changes?

折月煮酒 提交于 2020-01-09 11:06:34

问题


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.


回答1:


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




回答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.




回答3:


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.




回答4:


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.




回答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.



来源:https://stackoverflow.com/questions/5282507/how-to-run-a-function-in-javascript-every-time-a-variable-changes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!