简体   繁体   English

将观察者转换为辛烷值版本的正确方法是什么?

[英]What is the correct way to convert observer to octane version of ember?

I was trying to convert all my ember-component into OCTANE version.我试图将我所有的 ember 组件转换为 OCTANE 版本。 But I got a bigger doubt.但我有一个更大的疑问。 How can I convert the observer code into an OCTANE version?如何将observer代码转换为 OCTANE 版本? 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.注意:我尝试使用“@observer”,但它在组件内不起作用。

Ember Octane follows another programming model in that regard. Ember Octane 在这方面遵循另一个编程 model。 Instead of observing a property and updating another one whenever it changes, you should use a native getter to derive state.您应该使用本机 getter 来派生 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.传递给组件的 Arguments 被自动跟踪。 So in case value is not a local state but passed in as an argument, it's as simple as:因此,如果value不是本地 state 而是作为参数传入,则很简单:

import Component from '@glimmer/component';

export default class ChildComponent extends Component {
  get newValue() {
    return this.args.value / 12 * 2;
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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