I am using Angular2 + TypeScript and when I try execute this code:
var event = new Event('check');
window.dispatchEvent(event);
This code causing the next error:
failed to execute 'dispatchEvent' on 'EventTarget': parameter 1 is not of type 'Event'.
I have tried everything, and found out that this will work:
var event = new CustomEvent('check');
Problem is that CustomEvent is not supported by any IE.
Another thing that works is:
var event = new Event('CustomEvent');
event.initCustomEvent('check');
Problem is that InitCustomEvent is deprecated.
Is there anything I can do to avoid this type error? Maybe make an exception somewhere in typescript? Or use any code that is not deprecated and works for IE Edge?
Found a solution.
For some TypeScript settings, new Event is type of 'Event' only when we insert the second parameter, as this example:
window.addEventListener('check', e => console.log(e.type))
var event = new Event('check', { bubbles: true, cancelable: false })
document.body.dispatchEvent(event) // event will buble up to window
I found another answer in StackOverFlow .
Link: https://stackoverflow.com/a/37687099/6264260
if (event && event.originalEvent) {
var oe = event.originalEvent;
this.dispatchEvent(new oe.constructor(oe.type, oe));
}
It works for me very well .
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With