如何在 Typescript 中创建自定义事件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/43001679/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do you create custom Event in Typescript?
提问by Newbie2016
How do i create a customEvent Typescript and use it? I found this link on javascript on Mozilla site (https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent/CustomEvent)
如何创建 customEvent Typescript 并使用它?我在 Mozilla 网站 ( https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent/CustomEvent)上的 javascript 上找到了此链接
I am just doing some testing on custom Event but Typescript see it as an error. what i am planning on doing is add some extra data into the details property to use later: here is my code.
我只是对自定义事件进行一些测试,但 Typescript 将其视为错误。我打算做的是在 details 属性中添加一些额外的数据以供以后使用:这是我的代码。
let div:any=document.getElementById("my_div");
let c_event = new CustomEvent("build",{'details':3 });
div.addEventListener("build",function(e:Event){
console.log(e.details);
}.bind(this));
div.dispatchEvent(c_event);
回答by Diullei
The property name is detail
and not details
. The correct code needs to be:
属性名称是detail
而不是details
。正确的代码需要是:
let div: any = document.getElementById("my_div");
let c_event = new CustomEvent("build",{detail: 3});
div.addEventListener("build", function(e: CustomEvent) { // change here Event to CustomEvent
console.log(e.detail);
}.bind(this));
div.dispatchEvent(c_event);