I need to have methods and store bound to 'this' in my callback function, but when I use the spread operator it doesn't work. The reason for this as far as I know is that the spread operator returns a copy of the original. Therefore the proxy is never triggered.
What could I do in this case to make the proxy trigger?
const setup = function (options, cb) {
let store = new Proxy(options.store, {
set(target, prop, value) {
console.log(`changed ${prop} from ${target[prop]} to ${value}`);
target[prop] = value;
return true;
},
});
cb.bind(store)(); // Works as expected
// cb.bind({ ...store, ...methods })(); // Doesn't work
};
setup(
{
store: {
n: 123,
},
},
function () {
this.n = 456;
}
);
After removing the unbound
methods
variable, your example works as expected.You won't see the message being printed. That's to be expected, since the expression
{...store}
essentially clones the (proxy) objectstore
, with the effect that a new (regular) object is created and passed tobind
and modified there.