CustomEvent: CustomEvent() コンストラクター
Baseline Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.
CustomEvent()
コンストラクターは新しい CustomEvent
を作成します。
構文
js
new CustomEvent(type)
new CustomEvent(type, options)
引数
type
-
イベントの名前を表す文字列です。イベント名は大文字小文字を区別します。
options
省略可-
オブジェクトで、
Event()
で定義されるプロパティに加えて、以下のプロパティを指定することができます。detail
省略可-
イベントと関連付けられたイベント依存の値。この値は、ハンドラーが
CustomEvent.detail
プロパティを用いて利用できるようになります。 既定値はnull
です。
返値
新しい CustomEvent
オブジェクトです。
例
js
// カスタムイベントを作成
const catFound = new CustomEvent("animalfound", {
detail: {
name: "cat",
},
});
const dogFound = new CustomEvent("animalfound", {
detail: {
name: "dog",
},
});
// 適切なイベントリスナーを追加
obj.addEventListener("animalfound", (e) => console.log(e.detail.name));
// イベントの配信
obj.dispatchEvent(catFound);
obj.dispatchEvent(dogFound);
// "cat" および "dog" がコンソールの出力される
その他の例がイベントの作成と起動にあります。
仕様書
Specification |
---|
DOM # ref-for-dom-customevent-customevent |
ブラウザーの互換性
BCD tables only load in the browser