【问题标题】:How to call method of child component from parent in EmberJS如何在 EmberJS 中从父级调用子组件的方法
【发布时间】:2016-07-06 09:14:41
【问题描述】:

我遇到了一个有趣的问题,它不符合 Ember 的数据向下操作原则。

我有一个代码编辑器组件 (code-editor) 位于父组件 (request-editor) 内。编辑器组件上有一个方法可以在当前光标位置插入一个字符串。父组件包含一些用于将内容插入编辑器的按钮(例如当前日期)。

我认为我将按钮与编辑器分开是正确的,因为编辑器在没有这些按钮的情况下在其他地方使用。

在这个用例中使用绑定变量显然没有意义,因为它不是真正的数据,它想要执行一个动作。 IE。 {{code-editor insertText=insertText}} 没有意义。

如何有效地从父组件调用codeEditorChildComponent.insert()?我很欣赏它可能涉及将它们耦合在一起,但无论如何它们必须耦合才能工作。父组件已经由子组件组成。

【问题讨论】:

    标签: javascript ember.js


    【解决方案1】:

    所有的沟通都应该使用动作来完成。 我认为下面是一个好方法。你在request-editor 组件中有code_editor 属性,然后可以将操作发送到code-editor 组件。

    request-editor.hbs

    {{code-editor owner=this}}
    

    request-editor.js

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

    code-editor.js

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

    【讨论】:

    • 谢谢!我稍微调整了一下,因为我意识到我已经从 code-editor 准备好了一个动作,但你的回答让我意识到我可以通过该动作传递 this 然后将它的句柄存储在父组件中以供将来使用。
    猜你喜欢
    • 2021-05-17
    • 1970-01-01
    • 1970-01-01
    • 2016-12-08
    • 2020-06-15
    • 2021-05-02
    • 2015-07-28
    相关资源
    最近更新 更多