この文章は Salesforce 機械翻訳システムを使用して翻訳されました。詳細はこちらをご参照ください。
英語に切り替える

同期コードの結果を返す

aura:method は同期して実行されます。同期メソッドは、返す前に実行を終了します。同期 JavaScript コードから値を返すには、return ステートメントを使用します。

非同期メソッドは返した後も実行を続けることができます。JavaScript コードは、多くの場合コールバックパターンを使用して、非同期コードの終了後に結果を返します。非同期アクションの結果を返す方法については、後で説明します。

ステップ 1: マークアップで aura:method を定義する

同期コードを実行する logParam aura:method を見てみましょう。c:auraMethodCallerWrapper.app および「コンポーネントメソッドのコール」に示されたコンポーネントを使用します。aura:method を定義するマークアップは次のようになります。

1<!-- c:auraMethod -->
2<aura:component>
3    <aura:method name="logParam"
4      description="Sample method with parameter">
5        <aura:attribute name="message" type="String" default="default message" />
6    </aura:method>
7    
8    <p>This component has an aura:method definition.</p>
9</aura:component>

logParam aura:method には、名前が messageaura:attribute があります。この属性を使用して、logParam メソッドをコールするときに message パラメータを設定できます。

logParam の名前属性で、クライアント側コントローラの logParam() を呼び出すように aura:method を設定します。

aura:method には、複数の aura:attribute タグを使用できます。各 aura:attribute は、aura:method に渡すことができるパラメータに対応します。構文についての詳細は、aura:method を参照してください。

aura:method マークアップでは、戻り値を明示的に宣言しません。JavaScript コントローラで return ステートメントを使用します。

ステップ 2: コントローラで aura:method ロジックを実装する

logParam aura:method で、auraMethodController.jslogParam() を呼び出します。このソースを見てみましょう。

1/* auraMethodController.js */
2({
3    logParam : function(cmp, event) {
4        var params = event.getParam('arguments');
5        if (params) {
6            var message = params.message;
7            console.log("message: " + message);
8            return message;
9        }
10    },
11})

logParam() は単に渡されたパラメータを記録し、return ステートメントの使用方法を示すパラメータ値を返します。たとえば、非同期のサーバ側アクションコールを行わない同期コードの場合、return ステートメントを使用できます。

ステップ 3: 親コントローラから aura:method をコールする

c:auraMethodCallercallAuraMethod() で、その子コンポーネント c:auraMethod で定義された logParam aura:method をコールします。c:auraMethodCaller のコントローラは次のようになります。

1/* auraMethodCallerController.js */
2({
3    callAuraMethod : function(component, event, helper) {
4        var childCmp = component.find("child");
5        // call the aura:method in the child component
6        var auraMethodResult = 
7          childCmp.logParam("message sent by parent component");
8        console.log("auraMethodResult: " + auraMethodResult);
9    },
10})

callAuraMethod() は子コンポーネント c:auraMethod を検索し、aura:method のメッセージパラメータの引数がある logParam aura:method をコールします。

1childCmp.logParam("message sent by parent component");

auraMethodResult は、logParam から返された値です。

ステップ 4: aura:method へのコールを開始するボタンを追加する

c:auraMethodCaller マークアップには、auraMethodCallerController.jscallAuraMethod() を呼び出す lightning:button が含まれます。このボタンを使用して、子コンポーネントの aura:method へのコールを開始します。

1<!-- c:auraMethodCaller.cmp -->
2<aura:component >
3    <p>Parent component calls aura:method in child component</p>
4    <c:auraMethod aura:id="child" />
5    
6    <lightning:button label="Call aura:method in child component"
7        onclick="{! c.callAuraMethod}" />
8</aura:component>