12

我正在尝试在 ember 中构建一个模态框组件。模态框有两个标准按钮,“关闭”和“保存”。我想将控制器动作传递给这个组件,以便在单击保存按钮时,它会调用传递的控制器动作。我称我的组件为:

 {{#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 回答