0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

JavaScriptのCustomEventでイベントを自作する

Posted at

CustomEvent の解説

CustomEvent とは?

CustomEvent自分で名前をつけた独自のイベント を作成するためのオブジェクトです。
ブラウザの標準イベント(例:clickkeydownsubmit など)とは別に、アプリの都合に合わせて「特別な合図」を送ることができます。


書き方の基本

// CustomEvent の作成
const event = new CustomEvent('イベント名', {
  detail: データ // イベントと一緒に渡す追加情報(オプション)
})

// イベントを発火(dispatch)
window.dispatchEvent(event)

例:ファイルアップロード用イベント

// CustomEvent の作成
const uploadEvent = new CustomEvent('trigger-file-upload', {
  detail: { fileType: 'image', maxSize: 10 }
})

// 発火
window.dispatchEvent(uploadEvent)

受け取る側のコード例:

window.addEventListener('trigger-file-upload', (e) => {
  console.log('アップロードイベントを受け取りました!')
  console.log('詳細データ:', e.detail)
})

CustomEvent の特徴

  • イベントと一緒に 好きなデータ(detail を送れる。
  • window だけでなく、任意の DOM 要素でも使える。
  • 標準イベントと同様に addEventListener で監視できる。
  • コンポーネント間の疎結合な連携に便利。

注意点

  • イベントの名前は衝突しないようにユニークにする。
  • 大規模アプリでは乱用を避け、整理して使う。
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?