【问题标题】:Sending an action from a child component and catching it in a parent component从子组件发送一个动作并在父组件中捕获它
【发布时间】:2015-07-02 05:35:19
【问题描述】:

灰烬:1.13.2

我似乎无法正常工作。

父/子小部件(gridster-container/gridster-widget)

{{#gridster-container}}
    {{#each model as |widget|}}
        {{#gridster-widget sizeX=widget.sizeX sizeY=widget.sizeY action="addWidget"}}

           ...

        {{/gridster-widget}}
    {{/each}}
{{/gridster-container}}

gridster-widget

export default Ember.Component.extend({
  tagName : 'li',
  sizeX : 1,
  sizeY : 1,

  widget : null,

  didInsertElement : function() {
    var sizeX = this.get('sizeX');
    var sizeY = this.get('sizeY');
        //this.get('parentView').addWidget(this, sizeX, sizeY);
    //this.send('addWidget', this, sizeX, sizeY);
    //this.sendAction('action', this, sizeX, sizeY);
    //this.attrs.action(this, sizeX, sizeY);
    //this.get('gridsterContainer').send('addWidget', this, sizeX, sizeY);
    //this.action(this, sizeX, sizeY);
    this.sendAction('action', this, sizeX, sizeY); //I can see this executing in the debugger.
    }

});

在 gridster-container 组件中,我有以下动作来捕获动作。

  actions : {
    addWidget : function(widget, sizeX, sizeY) {
      alert('worked'); //This is never called
    }
  },

但是该操作从未被调用。

【问题讨论】:

  • 你在gridster-container模板中屈服了吗?如果是这样,组件是兄弟姐妹。

标签: ember.js


【解决方案1】:

当你屈服时,你需要传递parentView所以你的模板变成:

{{#gridster-container as |gridsterContainer|}}
    {{#each model as |widget|}}
        {{#gridster-widget parentView=gridsterContainer sizeX=widget.sizeX sizeY=widget.sizeY action="addWidget"}}

           ...

        {{/gridster-widget}}
    {{/each}}
{{/gridster-container}}

要么将gridster-widget 移动到gridster-container.hbs,然后您必须传递模型{{#gridster-container widgets=model}} 并循环它们。

【讨论】:

  • 不知道为什么,但通过parentView=gridsterContiner 仍然不起作用。我最终选择了您的第二个选项,并将小部件直接传递到 gridster-container。我在每个小部件中设置了parent=this。然后我就可以做到this.get('parent').send('addWidget',this, sizeX, sizeY) 并且成功了。
  • @jax 我会试一试并更新答案,这是未经测试的代码可能有语法错误 atm
【解决方案2】:

我无法对@Kitler 的回答发表评论,但这种语法对我有用,在 ember 1.13.4 中:

{{#gridster-container as |gridsterContainer|}}
    {{#each model as |widget|}}
        {{#gridster-widget targetObject=gridsterContainer sizeX=widget.sizeX sizeY=widget.sizeY action="addWidget"}}

            ...

        {{/gridster-widget}}
    {{/each}}
{{/gridster-container}}

targetObject 代替 parentView

与他们的回答一样,这假设您的 gridster-container.hbs 包括 {{yield this}}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-03-12
    • 2019-05-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-13
    • 1970-01-01
    相关资源
    最近更新 更多