[英]How to get the deleted item (for post-handling by proxy) if `length` property of array was decreased directly?
[英]How to get deleted or inserted item from proxy array?
我正在嘗試使用 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;
}
});
當前想法:我做了一些解決方法來從數組中獲取已刪除的項目,但它僅適用於pop()
方法,因為它從數組中刪除了最后一個項目。 但是我需要一種方法來獲得更改,即使它是使用splice
方法或push
或pop
。
謝謝。
[更新]我找到的解決方案:
https://github.com/ElliotNB/observable-slim我使用這個庫來檢測數組的變化,我也能夠檢測數組內嵌套屬性的變化。 這正是我正在尋找的。
我使用這個庫的原因是它使用代理。
我建議不要在 getter 上暴露實際的 traget。 您可以創建一個包裝函數來支持 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())
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.