灰烬:将子组件的动作发送到父组件

时间:2018-11-16 19:11:11

标签: javascript ember.js handlebars.js action

我正在尝试从父级调用/触发子级组件的动作。我已经尝试了几种方法,但是我什么都没得到。到目前为止,这基本上就是我所拥有的。
我试图通过将动作作为参数传递给向下传递的动作,将动作发送给父项。
这似乎有点像意大利面条的情况,但是我的项目组织方式是我的结果。

如果有人可以,请告诉我如何成功地将操作作为参数传递给父级。 (我很好奇,如果可能的话)
如果有人对如何调用孩子的动作还有更好的建议,请分享。预先感谢!

parent-component.hbs

{{child-component anAction=(action "anAction")}}
<div onclick={{action actionPassedFromChild}}></div>

parent-component.js

actionPassedFromChild: null,
....
actions: {
    parentAction(childAction){
       this.set('actionPassedFromChild', childAction);
    }
}


child-component.hbs

<div onclick={{action "anAction"}}

child-component.js

....
actions: {
    anAction(){
       this.parentAction(childAction);
    }
    childAction(){
       //Some operation
    }
}

在此示例中,如果我停止在“ anAction”内部的代码,则确实具有“ childAction”。但是,当它传递给“ parentAction”时,它是不确定的。谁能解释为什么?

1 个答案:

答案 0 :(得分:2)

似乎您有错别字。例如,parentAction不传递给子组件。但是,如果我了解您想要实现的目标是正确的-这是可行的,但是我什至无法想象您为什么需要这样做。

您可以使用我的示例here。选择位于子组件中,而按钮位于父组件中。当您在select-中选择某些内容时,子组件会将两个函数之一发送给父组件。而且,当您单击按钮时-父组件会调用该函数。

代码:

//child-component.js
import Ember from 'ember';


export default Ember.Component.extend({
  line1: "Say Hi!",
  line2: "Say Yeah!",

  changeAction(newAction) {
    switch (newAction) {
      case "1":
        this.onActionChange(this.action1);
        break;

      case "2":
        this.onActionChange(this.action2);
        break;

      default:
        this.onActionChange(undefined);
        break;
    }
  },

  action1: Ember.computed(function(){
    const that = this;
    return function() {
      alert(that.line1);
    }
  }),

  action2: Ember.computed(function(){
    const that = this;
    return function() {
      alert(that.line2);
    }
  })
});

//child-component.hbs
<select  onchange={{action changeAction value="target.value"}}>
        <option>Choose something</option>
        <option value="1">Action 1</option>
    <option value="2">Action 2</option>
</select>

//parent-component.js
import Ember from 'ember';

export default Ember.Component.extend({
  childishAction() {
    if (typeof this.childAction === 'function') {
      this.childAction();
    }
  }
});

//parent-component.hbs
{{child-component onActionChange=(action (mut childAction))}}
<div><button disabled={{unless childAction true false}} onclick={{action childishAction}}>Let's do it!</button></div>

这里会发生什么-当ember渲染模板时,您无法传递未定义的内容给action助手。因此,您需要将子组件发送的操作存储到某个变量中,并使用父组件的一些中间操作对其进行调用。

在我的示例中,从子组件返回的函数存储在父组件的childAction属性中,父组件的childishAction对其进行调用。

希望这会有所帮助。但是您可能试图以不正确的方式解决一些问题。

相关问题