1

Is there a way to intercept or override the array setter? For example:

var array = [];
array[2] = 10;
var myInterceptor = function(index, newVal) {
    do stuff when the array value at index is changed.
}

So I want myInterceptor to be called when the second line is executed. I am hoping to find a way to do it with Object.defineProperty()

danial
  • 4,058
  • 2
  • 32
  • 39

2 Answers2

0

Unfortunately, it's not possible to override the [] accessor for javascript arrays. There are a few other possibilities, though:

1) Override the push() method. This is reasonable to do for an individual array instance, but it strongly recommend that you do NOT change Array.prototype.push, as that could cause unintended side effects in other portions of javascript code.

2) Add a custom set() method. Again, while you could add this to the core Array prototype, it's strongly recommended that you do not. Functioning jsFiddle: http://jsfiddle.net/dmillz/RUcBM/

arr.set = function (index, value) {
    var oldValue = this[index];
    this[index] = value;
    $.event.trigger("array-change", [this, index, oldValue, value]); // jQuery event trigger, but feel free to use something else besides jQuery    
};

3) (Recommended) Create your own observable class that is backed by an array, or simply use a library that provides observable objects, such as Knockout's Observable Array, Ember's Observable, or Backbone's Model

Community
  • 1
  • 1
David Mills
  • 2,385
  • 1
  • 22
  • 25
0

What you can do is to use the Proxy class to intercept the set method.

var handler = { 
    set: (base,idx,val) => { 
        console.log('values:',base,idx,val); base[idx] = val; 
    } 
};

var mylist = new Proxy([],handler)
mylist[0] = 1
mylist
    > Proxy {0: 1}
Array.isArray(mylist)
    > true
Chris Claude
  • 973
  • 12
  • 25
Bill
  • 11
  • 2