这可能看起来很愚蠢,但在当今时代,如果数组的内容发生变化,人们应该能够期望 JS 引发事件。
关于在 变量 更改(定义 getter 或 setter)时收到通知的几个问题。而且好像有a way to do that (至少对于大多数浏览器包括 IE6+)
我的问题是,如果数组中的项目发生变化,我会收到通知:
var ar = ["one", "two", "three"];
// setting the whole array will call the custom setter method
// (assuming you defined it)
ar = ["one", "three", "five"];
// however, this will only call the getter method and won't call the setter
// without defining custom setters for every item in the array.
ar[1] = "two";
显然,我试图避免强制编码人员使用老式的 Java 风格 .getVale()
和 .setValue()
函数来访问/修改数据.
最佳答案
简而言之:不,你不能。你会注意到 Arrays不提供任何事件调度机制,并且它们的 API 不包含任何回调类型的功能。
更长的时间:正如其他人所指出的,可以包装数组……也可以轮询数组内容:
function watchArray(arr, callback) {
var oldVal = "" + arr;
setInterval(function() {
var curVal = "" + arr;
if (curVal != oldVal) {
callback();
oldVal = curVal;
}
}, 100);
}
但是这个方法有一些明显的问题:轮询,看一堆数组会变慢等。
关于javascript - 有没有办法在数组项值更改时获得回调?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10917536/