The purpose
To dispatch a custom event in TypeScript and trigger a process based on that event.
Implementation
Dispatch event
Here’s how you can dispatch the event with the code you’ve provided:
const event = new CustomEvent("event_name", { detail: { val1: "value 1", val2: "value 2" } });
dispatchEvent(event);
The "event_name" can be changed to any name you like.
The contents of the detail object can also be freely modified.
Receive event
Receiving the event is done as follows:
addEventListener("event_name", (e) => {
console.log ((e as CustomEvent).detail.val1+ (e as CustomEvent).detail.val2));
})
Change "event_name" to the name of the event you dispatched.
If you try to access e.detail directly without casting it as CustomEvent (e.g., e.detail), TypeScript will throw an error: “Property ‘detail’ does not exist on type ‘Event’.” This error will not occur in plain JavaScript.
Result
You’ve successfully learned how to send and receive any custom event in TypeScript.
Reference
DOM イベント - Web API | MDN
イベントは、コードの実行に影響を与える可能性のある「興味深い変化」をコードに通知するために発行されます。これは、マウス操作やウィンドウのサイズ変更などのユーザー操作や、環境の変化(バッテリー残量の低下や OS のメディアイベントなど)、その他の原因によって発行されます。

コメント