将控制器对象绑定到ember中的组件

时间:2013-09-27 19:58:11

标签: ember.js

我正在尝试在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 
    }

});

如何将控制器对象传递给组件?

感谢。

1 个答案:

答案 0 :(得分: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可以以任何方式重用。

请在此处查看解释概念的simple demo

希望它有所帮助。