是否有可能(使用jQuery或其他方式)侦听非DOM Javascript对象(或变量)的值的变化?所以,例如,我有:
function MyObject()
{
this.myVar = 0;
}
var myObject = new MyObject();
myObject.myVar = 100;
当myVar
的值发生变化并调用函数时,有没有办法监听?我知道我可以使用getter / setter,但以前版本的IE不支持它们。
答案 0 :(得分:11)
基本上你有两个选择
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*
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*
答案 1 :(得分:4)
答案 2 :(得分:1)
您基本上可以实现此类行为
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);