使用jQuery或其他方法,是否可以监听非DOM JavaScript对象(或变量)的值的更改?例如,我有:
function MyObject()
{
this.myVar = 0;
}
var myObject = new MyObject();
myObject.myVar = 100;
有没有一种方法可以监听 myVar
的值何时发生更改并调用一个函数?我知道我可以使用 getter/setters,但它们在早期版本的 IE 中不受支持。
使用jQuery或其他方法,是否可以监听非DOM JavaScript对象(或变量)的值的更改?例如,我有:
function MyObject()
{
this.myVar = 0;
}
var myObject = new MyObject();
myObject.myVar = 100;
有没有一种方法可以监听 myVar
的值何时发生更改并调用一个函数?我知道我可以使用 getter/setters,但它们在早期版本的 IE 中不受支持。
基本上你有两个选项
watch
方法,这只在Firefox中可用第三个跨平台的选择是使用轮询,这并不是很好
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*
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);
o.myVar = 100
不会起作用,必须是o.setMyVar(100)
。这就是我想避免的 - 我希望它像一个setter一样运行,但是当保持所有浏览器的支持时,似乎这是不可能的。 - redhotvengeance