有没有办法在数组项值发生变化时获得回调?

Man*_*ndo 5 javascript cross-browser dom-events

这可能看起来很愚蠢,但是在这个时代,如果数组的内容发生了变化,那么应该能够期望JS引发一个事件.

关于变量变化时通知的几个问题(定义getter或setter).似乎有办法做到这一点(至少对于大多数浏览器,包括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";
Run Code Online (Sandbox Code Playgroud)

显然,我试图避免强迫编码器使用老式的java风格.getVale()和.setValue()函数来访问/修改数据.

Man*_*ndo 0

好的,根据 @David Wolever 的代码和其他评论,实际上有一个解决方案:

使用John Dyer的注释来实现 addProperty 方法。在 getter 方法中放置一个 setTimeout ,以便在读取发生后不久与原始值进行比较:

addProperty(myObject, 'vals',
    function () {
        var _oldVal = "" + this._val;
        var _parent = this;
        console.log('getter!');
        setTimeout(function () {
            var curVal = "" + _parent._val;
            if (curVal != _oldVal)
                console.log('array changed!');
        }, 200);
        return this._val;
    },
    function (value) {
        console.log('setter!');
        this._val = value;
    });

    myObject.vals = ["one", "two", "three"];
    myObject.vals[1] = "five";
Run Code Online (Sandbox Code Playgroud)