Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dispatchEvent Causes error failed to execute 'dispatchEvent' on 'EventTarget': parameter 1 is not of type 'Event'

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?

like image 365
Roni Litman Avatar asked Jan 29 '17 11:01

Roni Litman


2 Answers

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
like image 111
Roni Litman Avatar answered Sep 20 '22 16:09

Roni Litman


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 .

like image 41
Lancer.Yan Avatar answered Sep 22 '22 16:09

Lancer.Yan