如何从父组件设置Ember组件的内部状态?

时间:2017-02-16 05:04:34

标签: javascript ember.js

我有一个表组件,它继承了几个行组件。每个行组件都有isSelected属性。

有一段时间我想重置所有行组件'来自表格isSelected操作(按钮)的false内的clear

我如何实现此功能?传递数据是否是改变组件内部状态的唯一方法?

行组件

export default Ember.Component.extend({
    tagName: 'tr',
    isSelected: false,
    classNameBindings: ['isSelected:selected'],

    click() {
        const data = this.get('data');
        const selectedState = this.get('isSelected');
        this._toggleSelected();

        if (selectedState) {
            this.sendAction('rowClicked', {data: data, operator: 'remove'});
        } else {
            this.sendAction('rowClicked', {data: data, operator: 'add'});
        }
    },

    _toggleSelected() {
        this.toggleProperty('isSelected');
    }
});

表格可选组件

export default Ember.Component.extend({
    selectedRows: [],
    classNames: ['table-selectable'],

    actions: {
        rowClicked(row) {
            this._addToSelectedRows(row);
        },

        cleanSelectedRows() {
            this._cleanSelectedRows();
        }
    },
    _addToSelectedRows(row) {
        console.log(row);
        this.get('selectedRows').addObject(row);
    },
    _cleanSelectedRows() {
        this.set('selectedRows', []);
    }
});

1 个答案:

答案 0 :(得分:1)

表由一些行组成。您可以在表中保留行的引用并调用它们的公共方法。

//row.js

    export default Ember.Component.extend({
      didInsertElement(){
        this._super(...arguments);
        this.get('table').registerRow(this);
      },

      setSelected(selected){
        this.set('isSelected', selected);
      }
    });


//table.js

    export default Ember.Component.extend({
      rows: Ember.computed(function(){return Ember.A();}),
      registerRow(row){
        this.get('rows').pushObject(row);
      },
      clearAll(){
        this.get('rows').forEach(function(row){
          row.setSelected(false);
        });
      }
    });


//table.hbs

{{table-row table=this}}