简体   繁体   English

如何在EmberJS中从父级调用子组件的方法

[英]How to call method of child component from parent in EmberJS

I've hit an interesting issue that doesn't fit with Ember's data down, actions up principle. 我遇到了一个有趣的问题,不符合Ember的数据,行动原则。

I have a code editor component ( code-editor ) sat inside a parent component ( request-editor ). 我有一个代码编辑器组件( code-editor )坐在父组件( request-editor )中。 There's a method on the editor component to insert a string at the current cursor position. 编辑器组件上有一个方法可以在当前光标位置插入一个字符串。 The parent component includes some buttons to insert things into the editor (eg the current date). 父组件包括一些用于将内容插入编辑器的按钮(例如,当前日期)。

I think I'm right in separating the buttons from the editor because the editor is used elsewhere without these buttons. 我认为我正确地将按钮与编辑器分开,因为编辑器在没有这些按钮的地方使用。

It obviously doesn't make sense to use a bound variable for this use-case because it's not really data, it's wanting to perform an action. 对于这个用例来说,使用绑定变量显然没有意义,因为它不是真正的数据,它想要执行一个动作。 Ie {{code-editor insertText=insertText}} makes no sense. {{code-editor insertText=insertText}}毫无意义。

How is it possible to effectively call codeEditorChildComponent.insert() from the parent component? 如何有效地从父组件调用codeEditorChildComponent.insert() I appreciate it will probably involve coupling them together but they have to be coupled for it to work anyway. 我很欣赏它可能会将它们耦合在一起,但它们必须耦合才能使它工作。 The parent component is composed of the child components already. 父组件已经由子组件组成。

All communications should be done using actions. 所有通信都应使用操作完成。 I think below is a good way. 我认为以下是一个好方法。 And you have code_editor property in request-editor component then could send action to code-editor component. 并且在request-editor组件中有code_editor属性,然后可以将操作发送到code-editor组件。

request-editor.hbs 请求editor.hbs

{{code-editor owner=this}}

request-editor.js 请求editor.js内

actions:{
  setChild(child){
    this.set('code_editor', child);
  }
}

code-editor.js 代码editor.js内

didInsertElement(){
  this._super(...arguments);
  this.get('owner').send('setChild', this);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM