svelte/action
アクション
アクションは要素が作成されたときに呼び出される関数です。このインターフェースを使用して、このようなアクションの型を指定できます。次の例では、<div>
要素でのみ動作し、オプションでパラメータを受け取り、パラメータに既定値が設定されているアクションを定義しています
export const const myAction: Action<HTMLDivElement, {
someProperty: boolean;
} | undefined>
myAction: type Action = /*unresolved*/ any
Action<HTMLDivElement, { someProperty: boolean
someProperty: boolean } | undefined> = (node: any
node, param: {
someProperty: boolean;
}
param = { someProperty: boolean
someProperty: true }) => {
// ...
}
Action<HTMLDivElement>
と Action<HTMLDivElement, undefined>
の両方が、アクションがパラメータを受け取らないことを示しています。
関数から update
と destroy
のメソッドを持つオブジェクトを返して、追加の属性とイベントの型を指定できます。詳細は ActionReturn
インターフェースを参照してください。
interface Action<
Element = HTMLElement,
Parameter = undefined,
Attributes extends Record<string, any> = Record<
never,
any
>
> {…}
<Node extends Element>(
...args: undefined extends Parameter
? [node: Node, parameter?: Parameter]
: [node: Node, parameter: Parameter]
): void | ActionReturn<Parameter, Attributes>;
ActionReturn
アクションは、このインターフェースで定義された 2 つのプロパティを含むオブジェクトを返すことができます。どちらも省略可能です。
- update: アクションにはパラメータがあります。このメソッドは、パラメータが変更されるたびに、Svelte がマークアップに更新を適用した直後に呼び出されます。
ActionReturn
とActionReturn<undefined>
のどちらも、アクションがパラメータを受け取らないことを意味します。 - destroy: 要素がアンマウントされた後に呼び出されるメソッド
さらに、アクションによって適用される要素に対していかなる属性やイベントを有効にするか指定することもできます。これは TypeScript タイピングにのみ適用され、ランタイムに影響を与えません。
使用例
interface Attributes {
Attributes.newprop?: string | undefined
newprop?: string;
'on:event': (e: CustomEvent<boolean>
e: interface CustomEvent<T = any>
CustomEvent<boolean>) => void;
}
export function function myAction(node: HTMLElement, parameter: Parameter): ActionReturn<Parameter, Attributes>
myAction(node: HTMLElement
node: HTMLElement, parameter: Parameter
parameter: type Parameter = /*unresolved*/ any
Parameter): type ActionReturn = /*unresolved*/ any
ActionReturn<type Parameter = /*unresolved*/ any
Parameter, Attributes> {
// ...
return {
update: (updatedParameter: any) => void
update: (updatedParameter: any
updatedParameter) => {...},
destroy: () => {...}
};
}
interface ActionReturn<
Parameter = undefined,
Attributes extends Record<string, any> = Record<
never,
any
>
> {…}
update?: (parameter: Parameter) => void;
destroy?: () => void;
前 次