简体   繁体   中英

How to set Ember component's internal state from parent component?

I have a table component which continas several row components. Each row component has a isSelected property.

Once a while I would like to reset all row components' isSelected inside to false from table's component clear action (a button).

How can I achive this functionality? Does passing data down is the only way to alter the internal state of a component?

Row Component

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');
    }
});

Table Selectable Component

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', []);
    }
});

A table is composed of some rows. You could keep references of rows in table and call their public methods.

//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}}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM