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

Dee*_*tha 12 ember.js

我试图在ember中构建一个模态框组件.模态框有两个标准按钮,"关闭"和"保存".我想将控制器操作传递给此组件,以便在单击"保存"按钮时,它会调用已传递的控制器操作.我将我的组件称为:

 {{#affi-modal-box title="Test title" modalId="createNewAnalyticsRunModal" controllerBinding=controller}}some message{{/affi-modal-box}}
Run Code Online (Sandbox Code Playgroud)

和我的组件:

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 
    }
Run Code Online (Sandbox Code Playgroud)

});

我有什么想法可以将控制器对象传递给组件?

谢谢.

int*_*xel 26

Ember.Component的工作方式是与应用程序的其他部分无关,因此,当您在组件中发生某些事情时传入要调用操作的控制器时,您更喜欢这样做:

{{#affi-modal-box 
  title="Test title" 
  modalId="createNewAnalyticsRunModal" 
  action="actionNameOnTheController"}}some message{{/affi-modal-box}}
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,您将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');
  }
});
Run Code Online (Sandbox Code Playgroud)

所以现在,只要onSaveButtonClick调用它,它就会将动作发送给actionNameOnTheController正在监听它的控制器.最重要的是,对控制器一无所知.这种功能使Ember.Component可以以任何方式重用.

请在此处查看解释概念的简单演示.

希望能帮助到你.

  • @ahnbizcad如果您要将组件与控制器紧密耦合,您甚至可能甚至不使用组件.组件的目的是解耦可重用性.因此,组件使用充当钩子的动作构建.并且根据组件的放置位置,这些操作可以触发不同的控制器操作,以执行在该上下文中最有用的操作.这有道理吗? (2认同)