12

ember でモーダル ボックス コンポーネントを構築しようとしています。モーダル ボックスには、「閉じる」と「保存」という 2 つの標準ボタンがあります。コントローラー アクションをこのコンポーネントに渡して、保存ボタンをクリックすると、渡されたコントローラー アクションが呼び出されるようにしたいと考えました。コンポーネントを次のように呼び出します。

 {{#affi-modal-box title="Test title" modalId="createNewAnalyticsRunModal" controllerBinding=controller}}some message{{/affi-modal-box}}

と私のコンポーネント:

AS.AffiModalBoxComponent = Ember.Component.extend({
attributeBindings: ['modelId','test'],
    //this is the function that gets called when save button is clicked 
    onSaveButtonClick : function(){

        console.log(this.controllerFor('analysisTemplates'));//fails
        console.log(this.get('controller'));//returns modal box component which I don't need 
    }

});

コントローラーオブジェクトをコンポーネントに渡す方法はありますか??

ありがとう。

4

1 に答える 1

26

Ember.Component の動作はアプリケーションの他の部分にとらわれないため、コンポーネントで何かが発生したときにアクションを呼び出すコントローラーを渡すのではなく、次のようにします。

{{#affi-modal-box 
  title="Test title" 
  modalId="createNewAnalyticsRunModal" 
  action="actionNameOnTheController"}}some message{{/affi-modal-box}}

ご覧のとおり、action属性をコントローラーのアクション名に設定し、コンポーネント内で呼び出すだけで、this.sendAction('action');以前に定義したアクション名がトリガーされます。

AS.AffiModalBoxComponent = Ember.Component.extend({
  attributeBindings: ['modelId','test'],
  //this is the function that gets called when save button is clicked 
  onSaveButtonClick : function(){
    this.sendAction('action');
  }
});

これで、onSaveButtonClickが呼び出されるたびに、actionNameOnTheControllerリッスンしているコントローラーにアクションが送信されます。そして何よりも、コントローラーについて何も知らなくても大丈夫です。これは、Ember.Component を何らかの方法で再利用可能にする機能の一種です。

ここで説明されているコンセプトの簡単なデモをご覧ください。

それが役に立てば幸い。

于 2013-09-27T20:32:00.233 に答える