-2

I want to know if there is a simple, clean way to listen for an array change in an array in Javascript.

I was attempting to use jQuery's change function but soon realized that it only works when the change is made in the HTML. I need to check if a change is made in Javascript, not HTML.

FeaturedSpace
  • 479
  • 3
  • 18
Procode238
  • 43
  • 7

2 Answers2

1

simple

Proxys can get quite messy when used for heavier lifting, and are limited when it comes to detecting adding or removing fields from objects, but they should work well for your use case. (mdn)

let array = new Proxy([], {
  set: (obj, prop, value) => {
    obj[prop] = value;
    if (prop === 'length')
      console.log(`array length changed to ${value}`);
    else
      console.log(`set index ${prop} to ${value}`);
    return true;
  }
});

array[5] = 3;
array.push(1);
array[0] = 10;
console.log(array);
junvar
  • 11,151
  • 2
  • 30
  • 46
0

Yes, object.watch (it's non-standard though). Here's my implementation that works in every current major browser.

FeaturedSpace
  • 479
  • 3
  • 18