监听 Javascript 对象值的变化
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6689931/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Listen for change to Javascript object value
提问by redhotvengeance
Is it possible (using jQuery or otherwise) to listen for a change in the value of a non-DOM Javascript object (or variable)? So, for instance, I have:
是否有可能(使用 jQuery 或其他方式)监听非 DOM Javascript 对象(或变量)的值的变化?因此,例如,我有:
function MyObject()
{
this.myVar = 0;
}
var myObject = new MyObject();
myObject.myVar = 100;
Is there a way to listen for when the value of myVar
changes and call a function? I know that I could use getter/setters, but they aren't supported in previous versions of IE.
有没有办法侦听值何时myVar
发生变化并调用函数?我知道我可以使用 getter/setter,但它们在以前版本的 IE 中不受支持。
采纳答案by mplungjan
If IE is important, I guess you are not interested in Watch
如果 IE 很重要,我猜你对Watch不感兴趣
But someone seems to have written a shim which makes this question a duplicate
但似乎有人写了一个垫片,使这个问题重复
回答by Andris
Basically you have two options
基本上你有两个选择
- use non-standard
watch
method which is available only in Firefox - use getters and setters which are not supported in older IE versions
- 使用
watch
仅在 Firefox 中可用的非标准方法 - 使用旧版 IE 不支持的 getter 和 setter
The third and cross-platform option is to use polling which is not so great
第三个跨平台选项是使用轮询,这不是很好
Example of watch
示例 watch
var myObject = new MyObject();
// Works only in Firefox
// Define *watch* for the property
myObject.watch("myVar", function(id, oldval, newval){
alert("New value: "+newval);
});
myObject.myVar = 100; // should call the alert from *watch*
Example of getters
and setters
getters
和的例子setters
function MyObject(){
// use cache variable for the actual value
this._myVar = undefined;
}
// define setter and getter methods for the property name
Object.defineProperty(MyObject.prototype, "myVar",{
set: function(val){
// save the value to the cache variable
this._myVar = val;
// run_listener_function_here()
alert("New value: " + val);
},
get: function(){
// return value from the cache variable
return this._myVar;
}
});
var m = new MyObject();
m.myVar = 123; // should call the alert from *setter*
回答by Alexander Beletsky
You can basically implement such behavior
你基本上可以实现这样的行为
function MyObject(onMyVarChangedCallback)
{
this.myVar = 0;
this.setMyVar = function (val) {
this.MyVar = val;
if (onMyVarChangedCallback) {
onMyVarChangedCallback();
}
}
}
function onChangeListener() {
alert('changed');
}
var o = new MyObject(onChangeListener);