问题描述
我正在使用Angular2 + TypeScript,当我尝试执行此代码时:
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:
我已经尝试了所有方法,发现可以使用:
I have tried everything, and found out that this will work:
var event = new CustomEvent('check');
问题在于,任何IE都不支持CustomEvent.
Problem is that CustomEvent is not supported by any IE.
另一种可行的方法是:
var event = new Event('CustomEvent');
event.initCustomEvent('check');
问题是不建议使用InitCustomEvent.
Problem is that InitCustomEvent is deprecated.
有什么办法可以避免这种类型的错误?也许在打字稿中的某个地方例外?还是使用任何不被弃用且适用于IE Edge的代码?
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?
推荐答案
找到了解决方案.
对于某些TypeScript设置,仅当我们插入第二个参数时,新事件就是事件"类型,例如:
For some TypeScript settings, new Event is type of 'Event' only when we insert the second parameter, as this example:
var event = new Event("check", { bubbles: true, cancelable: false });
window.dispatchEvent(event);
这篇关于dispatchEvent导致错误,无法在'EventTarget'上执行'dispatchEvent':参数1不是'Event'类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!