如何从代理数组中删除或插入项目?

Joh*_*man 6 javascript arrays es6-proxy

我正在尝试使用JavaScript代理来检测对象数组中的更改。

问题:每当删除或插入数组发生变化时,我都希望得到该删除或插入的项目。

当前代码

target = [{ id: 1, a: 'a' }, { id: 2, a: 'b' }];
proxy = new Proxy(target, {
    get: function (target, property: string, receiver) {
        if (property === 'pop') {
            console.log('deleted object', target[target.length - 1]);
        }
        console.log('get', property);
        // property is index in this case
        return target[property];
    },
    set: function (target, property, value, receiver) {
        console.log('set', property, 'to', value);
        target[property] = value;
        // you have to return true to accept the changes
        return true;
    }
});
Run Code Online (Sandbox Code Playgroud)

当前的想法: 我做了一些变通方法来从数组中获取已删除的项目,但它仅适用于pop()方法,因为它会删除数组中的最后一个项目。但是我需要一种方法来获取更改,即使它是使用splicemethod或pushor进行的pop

谢谢。

[更新] 我发现的解决方案:

https://github.com/ElliotNB/observable-slim 我使用此库来检测数组中的更改,我也能够检测到数组内嵌套属性的更改。这正是我在寻找的东西。

我使用此库的原因是因为它使用代理。

xde*_*akv 0

我建议不要在 getter 上暴露实际的目标。您可以创建一个包装函数来支持 cutosom 修饰符。看看下面的例子。

const target = [
  { id: 1, a: "a" },
  { id: 2, a: "b" },
];
const proxy = new Proxy(target, {
  get: function (target, property, receiver) {
    switch (property) {
      case "push":
      case "pop":
      case "slice":
      case "splice":
        return (...arg) => target[property](...arg);
    }
    throw Error("Not supported yet");
  },
});

proxy.push({ id: 3, a: "c" })
console.log(proxy.pop())
console.log(proxy.slice(1,2))
console.log(proxy.pop())
Run Code Online (Sandbox Code Playgroud)