【发布时间】:2011-03-29 00:47:03
【问题描述】:
https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Object/watch
.watch() 方法简而言之就是:“监视要分配值的属性并在发生这种情况时运行函数。”
长描述形式:“监视分配给此对象中名为 prop 的属性,每当设置 prop 时调用 handler(prop, oldval, newval) 并将返回值存储在该属性中。观察点可以过滤(或无效)赋值,通过返回一个修改后的 newval(或通过返回 oldval)。”
这里有一个让它在所有浏览器中工作的问题:Object.watch() for all browsers?
我正在寻找类似的东西。我正在寻找的是一种我可以用来适应这个规范的方法:“监视分配给这个对象中的任何属性并在发生这种情况时运行一个函数。”主要区别在于它是任何属性,并且只是任何特定属性。
有人可以创建这样的方法,或者如果他们知道这样的方法已经存在,链接到它吗?让它在所有浏览器中工作(减去 IE,或者如果 IE9 符合,则减去 IE8)会很有用
编辑:举个例子来说明我的意思,我会展示我需要它的用途。
var DiscreteLine = function (leftBound, length){
this.positive = [];
this.negative = [];
this.length = length;
this.leftBound = leftBound;
this.rightBound = leftBound + length
if (this.leftBound < 0){
this.negative.length = (leftBound * -1) + 1;
} else {
this.negative.length = 0;
}
if (this.rightBound >= 0){
this.positive.length = rightBound + 1;
} else {
this.positive.length = 0;
}
this.watchObject = new ObjectWatcher(handler(prop, oldval, newval){ /* some stuff */ });
}
然后,例如,如果有人做了以下事情:
theLine = new DiscreteLine(-2, 4);
theLine[-8] = 10;
处理程序将调用参数(“-8”,未定义,10)。 (最终会发生的是,脚本会自动重新计算 leftBound 和 length 属性(就像数组如何自动更新 length 属性一样)。
【问题讨论】:
标签: javascript watch