Things I want to do
We’ll use TypeScript to trigger custom events and then use those events as triggers for processing.
implementation
Send an event
The following code will send the event.
const event = new CustomEvent("event_name", { detail: { val1: "value 1", val2: "value 2" } });
dispatchEvent(event);Replace ‘event_name’ with any name you like.
The contents of the detail object can be freely modified.
Receiving an event
The event received is as follows:
addEventListener("event_name", (e) => {
console.log ((e as CustomEvent).detail.val1+ (e as CustomEvent).detail.val2));
})Replace ‘event_name’ with the name of the event that triggered the event.
When accessing the detail property using `e.detail` without specifying `as CustomEvent`, you will get the error ‘Property detail does not exist on type Event .’ (This error does not occur in JavaScript.)
Result
I was able to send and receive arbitrary custom events using TypeScript.
Websites I used as references
DOM イベント - Web API | MDN
イベントは、コードの実行に影響を与える可能性のある「興味深い変化」をコードに通知するために発行されます。これは、マウス操作やウィンドウのサイズ変更などのユーザー操作や、環境の変化(バッテリー残量の低下や OS のメディアイベントなど)、その他の原因によって発行されます。


コメント