イベント
stencil eventsのようなものはありません。代わりに、StencilはDOMイベントの使用を推奨しています。
ただし、Stencilは、コンポーネントが発行できるイベントと、コンポーネントがリッスンするイベントを指定するためのAPIを提供します。 これは、 Event()および Listen()デコレータを使用して行われます。
イベントデコレータ
コンポーネントは、イベントエミッタデコレータを使用してデータとイベントを発行できます。
カスタムDOMイベントをディスパッチして他のコンポーネントを処理するには、@Event()デコレータを使用します。
import { Event, EventEmitter } from '@stencil/core';
...
export class TodoList {
@Event() todoCompleted: EventEmitter<Todo>;
todoCompletedHandler(todo: Todo) {
this.todoCompleted.emit(todo);
}
}
上記のコードは、todoCompletedと呼ばれるカスタムDOMイベントをディスパッチします。
Event(opts: EventOptions)デコレータは、オプションでオプシ ョンオブジェクトを受け入れて、ディスパッチされたイベントの動作を形成します。 オプションとデフォルトについては、以下で説明します。
export interface EventOptions {
/**
* デフォルトをオーバーライドする文字列カスタムイベント名。
*/
eventName?: string;
/**
* イベントがDOMを介してバブルアップするかどうかを示すブール値。
*/
bubbles?: boolean;
/**
* イベントがキャンセル可能かどうかを示すブール値。
*/
cancelable?: boolean;
/**
* イベントがShadowDOMと通常のDOMの境界を越えてバブルできるかどうかを示すブール値。
*/
composed?: boolean;
}
例:
import { Event, EventEmitter } from '@stencil/core';
...
export class TodoList {
// Event called 'todoCompleted' that is "composed", "cancellable" and it will bubble up!
@Event({
eventName: 'todoCompleted',
composed: true,
cancelable: true,
bubbles: true,
}) todoCompleted: EventEmitter<Todo>;
todoCompletedHandler(todo: Todo) {
const event = this.todoCompleted.emit(todo);
if(!event.defaultPrevented) {
// 防止されていない場合は、デフォルトの処理コードを実行します
}
}
}
注記
In the case where the Stencil Event type conflicts with the native web Event type, there are two possible solutions:
- Import aliasing:
import { Event as StencilEvent, EventEmitter } from '@stencil/core';
@StencilEvent() myEvent: EventEmitter<{value: string, ev: Event}>;
- Namespace the native web
Eventtype withglobalThis:
@Event() myEvent: EventEmitter<{value: string, ev: globalThis.Event}>;