Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you create custom Event in Typescript?

Tags:

typescript

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)

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.

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);
like image 872
Newbie2016 Avatar asked Mar 24 '17 14:03

Newbie2016


People also ask

How do you create a event in TypeScript?

let div: HTMLElement | null = document. getElementById("my_div"); let c_event = new CustomEvent<number>("build", {detail: 3}); div. addEventListener("build", function(e: CustomEvent<number>) { // change here Event to CustomEvent console. log(e.

How do I create a custom event?

A custom event can be created using the CustomEvent constructor: const myEvent = new CustomEvent("myevent", { detail: {}, bubbles: true, cancelable: true, composed: false, }); As shown above, creating a custom event via the CustomEvent constructor is similar to creating one using the Event constructor.


2 Answers

The property name is detail and not details. The correct code needs to be:

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);
like image 171
Diullei Avatar answered Sep 28 '22 12:09

Diullei


Simplest way is like so:

window.addEventListener("beforeinstallprompt", ((event: CustomEvent) => {
   console.log("Whoop!");
}) as EventListener);
like image 26
sidonaldson Avatar answered Sep 28 '22 10:09

sidonaldson