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