Reputation: 3802
I was trying to convert all my ember-component into OCTANE version. But I got a bigger doubt. How can I convert the observer
code into an OCTANE version? For example,
parent.hbs
<Child @value={{this.value}} />
child.hbs
<div>{{this.newUpdate}}</div>
child.js
export default class ChildComponent extends Component {
/** Previous code: sample code only
valueUpdate: observer('value', function() {
this.newValue = this.value / 12 * 2;
})
*/
}
How can I update the observer into octane way? Any idea please...
Note: I tried using '@observer' but it didn't work inside the component.
Upvotes: 6
Views: 1972
Reputation: 6338
Ember Octane follows another programming model in that regard. Instead of observing a property and updating another one whenever it changes, you should use a native getter to derive state.
import Component from '@glimmer/component';
import { tracked } from '@glimmer/tracking';
export default class ChildComponent extends Component {
// I assume that value is a local state of this component.
// If it's an argument passed to the component on invocation.
// You don't need to declare it here but can reference
// this.args.value directly in the getter.
@tracked value;
get newValue() {
return this.value / 12 * 2;
}
}
As long as the value is derived from a tracked property the template will rerender whenever it changes. No need to manually update a value using an observer or explicitly list dependency as you needed to do with computed properties.
Arguments passed to components are autotracked. So in case value
is not a local state but passed in as an argument, it's as simple as:
import Component from '@glimmer/component';
export default class ChildComponent extends Component {
get newValue() {
return this.args.value / 12 * 2;
}
}
Upvotes: 5