繁体   English   中英

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

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

我试图将我所有的 ember 组件转换为 OCTANE 版本。 但我有一个更大的疑问。 如何将observer代码转换为 OCTANE 版本? 例如,

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;
        })
      */
  }

如何将观察者更新为辛烷值? 有什么想法请...

注意:我尝试使用“@observer”,但它在组件内不起作用。

Ember Octane 在这方面遵循另一个编程 model。 您应该使用本机 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;
  }
}

只要该值是从跟踪的属性派生的,模板就会在其更改时重新呈现。 无需像使用计算属性那样使用观察者手动更新值或显式列出依赖项。

传递给组件的 Arguments 被自动跟踪。 因此,如果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