Is there a way to get a callback when the value of an array element has changed?

This may seem silly, but nowadays, you can expect JS to raise an event if the contents of the array have changed .

Several questions were asked about receiving notifications when a variable changes (specify the recipient or installer). And there seems to be a way to do this (at least for most browsers, including IE6 +)

My problem is that I am trying to get a notification if an element in an array changes:

    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";

Obviously, I try not to force the encoder to use Java old school functions .getVale()and .setValue()to access / modify data.

+5
3

, @David Wolever , :

John Dyer addProperty. 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";
0

: , . , , API .

: , ... :

function watchArray(arr, callback) {
    var oldVal = "" + arr;
    setInterval(function() {
        var curVal = "" + arr;
        if (curVal != oldVal) {
            callback();
            oldVal = curVal;
        }
    }, 100);
}

: , ..

+3

I think that based solutions are timeoutnot the best.
If you can use push and pop to change your array, you can override methods pushand popprototype Array(or just some object that you want to control):

var myWatchableArr = [];
myWatchableArr.setChangeCallback = function(callback){
    this.changeCallback = callback;
}
myWatchableArr.push = function(e){
    Array.prototype.push.call(this,e);
    if(typeof this.changeCallback == "function")
      this.changeCallback(this);
}
myWatchableArr.push(3);
myWatchableArr.setChangeCallback(function(arr){
    console.log("the array has been changed", arr);
});
// now watching for changes
myWatchableArr.push(4);

If push and pop are not enough, you can add some method setAtto use as myWatchableArr.setAt(3, value)instead myWatchableArr[3]=value.

0
source

All Articles