Skip to content Skip to sidebar Skip to footer

Es6 Proxy: Set() Trap Not Triggering, When Setting Inside Target Object's Method

Example: let foo = {bar: 'baz', method() { this.bar = 'baz2' }} let fooProxy = new Proxy(foo, {set(target, key, val) { console.log('set trap triggered!') }}) fooProxy.bar = 'any v

Solution 1:

The set trap is not triggered because the this that you are accessing within method() is not the proxy but the original object foo. A proxy does not change the original object. You can see this by checking what this is inside method():

let foo = {
  method () {
    returnthis === fooProxy
  }
}
let fooProxy = newProxy(foo, {})
document.write(foo.method()) //=> false

You could instead explicitly set the context of method() on invocation by using Function#call:

let foo = {bar: 'baz', method() { this.bar = 'baz2' }}
let fooProxy = newProxy(foo, {set(target, key, val) { console.log('set trap triggered!') }})

fooProxy.bar = 'any value'//=> set trap triggered!
foo.method.call(fooProxy) //=> set trap triggered!

Solution 2:

You can also add the proxy to the object prototype.

SomeObject.prototype = newProxy(
    SomeObject.prototype,
    SomeObjectHandlerProxy
);

instance = newSomeObject();

something like should work

Solution 3:

In foo.method you're not setting a propery through the proxy object, so obviously no trap is triggered. A Proxy does not modify the original object.

Post a Comment for "Es6 Proxy: Set() Trap Not Triggering, When Setting Inside Target Object's Method"