父组件中的Ember数据更改未在UI上反映

时间:2018-03-25 04:42:19

标签: javascript jquery ember.js

我有一个父组件,它有一个手风琴面板(有多个/动态行数)

{{#my-accordion accordionPanels=accordionPanels as |accordion| }}
{{my-details-row section=accordion.props.section removeRow='removeRow'}}
{{/my-accordion}}

相应的JS如下;

accordionPanels: function() {
    var accordionPanels = [];
    var self = this;
    var myRows = this.get('section').myRows;
    myRows.forEach(function(myRow) {
        accordionPanels.pushObject({
            panel: {
                name: myRow.rowId,
                props: {
                    section: myRow
                }
            }
        });
    });

    return accordionPanels;
}.property('section.myRows'),

actions: {
    removeRow: function(row){
        var numberContainers = this.get('section').myRows.length;
        for (var i = 0; i < numberContainers; i++){
            if(this.get('section').myRows.contains(row.name)){
                console.log("row found!");
                this.get('section').myRows.removeObject(row.name);
            }
        }
    },
}   

子组件(my-details-row)代码如下

actions: {
    removeRow: function(row){
        this.sendAction('removeRow', row);
    }
}

儿童hbs如下;

<div class="dataBlockItem">
    {{my-field field=(field-from-section section "SECTION_NAME" "FIELD_NAME") }}
</div>  
{{my-button label="Remove" action="removeRow"}}

现在,当单击“删除”按钮时,我希望删除相应的行。虽然我确实在父母那里得到了行动(从孩子那里传来), 甚至在执行

之后
  

this.get(&#39;节&#39)。myRows.removeObject(row.name);

UI未更新(即父级中的数据更改未反映在子组件中)

我是否需要编写其他代码/逻辑才能反映UI上的更改?

1 个答案:

答案 0 :(得分:1)

你走在正确的轨道上。您应该能够使用闭包操作来帮助简化父和子组件操作的连接。请在下面的链接中查看以下代码和一个非常基本的例子Ember Twiddle。此外,您可能已经看过这个,但以下是这里是Ember.js指南的链接,它提供了组件操作的说明。 Ember Component Actions -version 2.15

父component.hbs

{{#my-accordion accordionPanels=accordionPanels as |accordion| }}
  {{my-details-row section=accordion.props.section removeRow=(action 'removeRow' accordion)}}
{{/my-accordion}}

父组件.js

- 这里可以通过简单地传递行对象本身.removedObject(row)

来删除行
actions: {
  removeRow: function(row){
    var numberContainers = this.get('section.myRows').length;
    for (var i = 0; i < numberContainers; i++){
      if(this.get('section.myRows').includes(row.name)){
        console.log("row found!");
        this.get('section.myRows').removeObject(row);
      }
    }
  },
}   

Child component.hbs

- 此处将removeRow操作绑定到按钮组件的点击事件

<div class="dataBlockItem">
    {{my-field field=(field-from-section section "SECTION_NAME" "FIELD_NAME") }}
</div>  
{{my-button label="Remove" click=removeRow}}

Child component.js

- 此处不必定义removeRow函数。

actions: {
  // No need to define the removeRow function
}

Example Ember Twiddle --using ember.js@2.2.2 to show the rough compatibility of the above approach