简体   繁体   中英

How to listen parent component value change in child component ember octane?

This is my code

parent.hbs
 
 <ChildComp
   @value={{this.changes}}
 />


parent.js
export class ParentComponet extends Component {
  @tracked this.changes = [1,2,3]
  
  @action addChanges() {
     this.changes = [...this.changes, this.changes.length]
  }
}

child-comp.js
export class ChildComponet extends Component {
   // I wanted to observe this.args.changes updated
   // Based on that I need to call some operation
   get operation() {
      let parent = this.args.values.map((obj) {
            if (obj.parent !== null) {
             set(obj, 'goal', null);
             set(obj, 'newSubGoal', null);
            }
    });
   }
}

I wanted to observe this.args.changes in my child compoent. How can I do that in ember-octane way?

I'm assuming that you are using the latest Octane features in you app from your code snippet.

We can make a class property reactive using the @tracked decorator. By this, when a tracked value changes in the parent component, the same change will be propogated into all the places where its being utilized. In your case, you have passed the value into child component and thus, the changes will also tracked inside the child component.

parent component class:

export class ParentComponent extends Component {
  @tracked changes = [1,2,3];
  
  @action addChanges() {
     this.changes = [...this.changes, this.changes.length]
  }
}

In you child component you can use getters to recompute the changes accordingly. getter will be recomputed on every time a value accessed inside the getter changes. For instance, from your code, if you need to get the sum of the array,

child component class:

export class ChildComponent extends Component {
   // This getter will be computed every time the `changes` array changes.
   get sum() {
     return this.args.value.reduce((a, b) => a + b, 0);
   }
}

child template:

SUM: {{this.sum}}

EDIT

If you need to run an arbitrary function when a value changes (most to be used to sync with external libraries or manual DOM mutations), you can use {{did-update}} modifier of ember-render-modifiers

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