dispatchEvent(new Proxy(event, {}) does not work

Viewed 408

I'm working on an app which uses events. The modules of the app execute in separate containers and I thought about using Proxy to tame the events that are fired. However, I cannot seem to be able to make dispatchEvent accept an event that has been proxied.

The following fails:

let event = new CustomEvent('my event');
let eventProxy = new Proxy(event, {});
let eventTarget = document.createElement('div');

try {
    eventTarget.dispatchEvent(eventProxy); // VM134:4 Uncaught TypeError: Failed to execute 'dispatchEvent' on 'EventTarget': parameter 1 is not of type 'Event'
} catch(error) {
    console.log(error.message);
}

Anyone has any ideas how dispatchEvent can be made to accept proxies?

1 Answers

Could be an old question, but It may help someone, because I didn't find similar Q&As about this.

As pointed in the comments:

Proxy will not create a fully transparent replacement object.

You can also log out eventProxy and see that most of the properties are unaccusable.

My suggestion is wrapping your Event with an object that has a function that returns the event. (for multiple events, you can even use that object for a gateway to all events).

Then, dispatch the event that returns by calling that function.

Now, when you proxy the new object, you can override the get in the handler to log the call.

let event = new CustomEvent('my event');
let eventWrapper = { getEvent: ()=> event };
let handler = {
get: function(target, thisArg, argumentsList) {
    console.log('Logged!');
    return Reflect.get(...arguments)
  }
}
let eventProxy = new Proxy(eventWrapper, handler);
let eventTarget = document.createElement('div');

try {
    eventTarget.dispatchEvent(eventProxy.getEvent());
    console.log("Done!")
} catch(error) {
    console.log(error.message);
}

Related