簡體   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