Reputation: 573
So far I have understood ES6 proxies as a way to add intercepts to allow you to add custom behavior to your code. Implemented this code snippet to intercept a push into an array but it logs an extra the extra 'trapped! 1' after a push and I cannot figure out why. Does anyone know why it does this? And does this mean the code in the trap is run twice?
const handler = {
set(target, propertyKey, value, receiver) {
console.log('trapped!', value);
return Reflect.set(target, propertyKey, value, receiver);
}
};
const p = new Proxy([], handler);
p.push('a')
Upvotes: 0
Views: 44
Reputation: 13912
It's setting the length as well as the index of the array you're pushing onto. That's why it runs twice for every push.
let handler = {
set(target, propertyKey, value, receiver) {
console.log(`set ${propertyKey} to ${value}`)
return Reflect.set(target, propertyKey, value, receiver);
}
};
const p = new Proxy([], handler);
p.push('a')
Upvotes: 2