使用Proxy对象检测Javascript数组中的更改

w2o*_*ves 29 javascript

在Javascript中观察数组中的更改是相对微不足道的.

我使用的一种方法是这样的:

// subscribe to add, update, delete, and splice changes
Array.observe(viewHelpFiles, function(changes) {
  // handle changes... in this case, we'll just log them 
  changes.forEach(function(change) {
    console.log(Object.keys(change).reduce(function(p, c) {
      if (c !== "object" && c in change) {
        p.push(c + ": " + JSON.stringify(change[c]));
      }
      return p;
    }, []).join(", "));
  });
});
Run Code Online (Sandbox Code Playgroud)

但是,我最近读过的Array.observe是不推荐使用的,我们应该使用代理对象.

我们如何检测Proxy对象中数组的变化?我无法找到任何有兴趣详述的例子吗?

Ice*_*kle 43

从我可以从MDN页面读取的内容,您可以创建一个通用处理程序,您可以在其中处理对任何对象的所有更改.

从某种意义上说,你编写了一个拦截器,每当你从数组中获取一个值或设置一个值时它就会介入.然后,您可以编写自己的逻辑来跟踪更改.

var arrayChangeHandler = {
  get: function(target, property) {
    console.log('getting ' + property + ' for ' + target);
    // property is index in this case
    return target[property];
  },
  set: function(target, property, value, receiver) {
    console.log('setting ' + property + ' for ' + target + ' with value ' + value);
    target[property] = value;
    // you have to return true to accept the changes
    return true;
  }
};

var originalArray = [];
var proxyToArray = new Proxy( originalArray, arrayChangeHandler );

proxyToArray.push('Test');
console.log(proxyToArray[0]);

// pushing to the original array won't go through the proxy methods
originalArray.push('test2');

// the will however contain the same data, 
// as the items get added to the referenced array
console.log('Both proxy and original array have the same content? ' 
  + (proxyToArray.join(',') === originalArray.join(',')));

// expect false here, as strict equality is incorrect
console.log('They strict equal to eachother? ' + (proxyToArray === originalArray));
Run Code Online (Sandbox Code Playgroud)

然后输出:

getting push for 
getting length for 
setting 0 for  with value Test 
setting length for Test with value 1
getting 0 for Test
Test
Run Code Online (Sandbox Code Playgroud)

代理的警告是,在对象上定义的所有内容都将被拦截,这在使用该push方法时可以被观察到.

将被代理的原始对象不会发生变异,并且代理不会捕获对原始对象所做的更改.

  • 但是您根本没有观察数组​​,您创建了一个代理,代理将更改转发到数组。问题是如何实际观察数组本身。将代理命名为“arrayToObserve”具有误导性。那些代理和数组是两个完全不同的对象。 (3认同)
  • 一个警告,IE11 不支持。 (2认同)
  • @Chexpir是的,根据MDN它甚至完全不支持IE,但它应该得到Edge的支持,这是当前的MS浏览器 (2认同)

cod*_*rek 5

你可以做这样的事情

new Proxy([], {
    get(target, prop) {
        const val = target[prop];
        if (typeof val === 'function') {
            if (['push', 'unshift'].includes(prop)) {
                return function (el) {
                    console.log('this is a array modification');
                    return Array.prototype[prop].apply(target, arguments);
                }
            }
            if (['pop'].includes(prop)) {
                return function () {
                    const el = Array.prototype[prop].apply(target, arguments);
                    console.log('this is a array modification');
                    return el;
                }
            }
            return val.bind(target);
        }
        return val;
    }
});
Run Code Online (Sandbox Code Playgroud)