カスタムイベントを作成・発火して疎結合なコンポーネント通信を行う
// ── カスタムイベント: 独自のイベントを作成・発火する ────
// コンポーネント間の通信などに使う
// ── カスタムイベントを定義して発火 ───────────────────
// CustomEvent(イベント名, { detail: 付属データ })
const userEvent = new CustomEvent('user:login', {
detail: {
userId: '123',
userName: '田中',
timestamp: Date.now(),
},
bubbles: true, // 親要素にも伝播させる
cancelable: true, // preventDefault() で取り消し可能にする
});
// 発火(どの要素にも発火できる)
document.dispatchEvent(userEvent);
// ── イベントを受け取る ────────────────────────────────
document.addEventListener('user:login', (event) => {
const e = event as CustomEvent<{ userId: string; userName: string }>;
console.log('ログイン:', e.detail.userName);
console.log('ユーザーID:', e.detail.userId);
});
// ── TypeScript で型安全なカスタムイベントを作る ────────
type UserLoginEvent = CustomEvent<{ userId: string; userName: string }>;
function dispatchLogin(userId: string, userName: string) {
const event: UserLoginEvent = new CustomEvent('user:login', {
detail: { userId, userName },
bubbles: true,
});
document.dispatchEvent(event);
}コンポーネント間のカスタムイベントバスとして使える。TypeScriptでは型引数でdetailの型を指定できる(CustomEvent<T>)。