簡體   English   中英

監聽 EmberJs Octane 組件中的服務屬性更改

[英]Listening to a service property change in an EmberJs Octane Component

我想知道 Emberjs Octane 在服務屬性更改后如何在組件中觸發 function。 這是我在 Octane 之前如何做的一個例子。

Octane 之前的 child-component.js

import Component from '@ember/component';
import {inject as service} from '@ember/service';
import {computed, observer} from '@ember/object';
import { isEmpty } from '@ember/utils';
import { on } from '@ember/object/evented';
export default Component.extend({

userAccount: service(),
childNavigation: service(),

whenUserChanges: on('init', observer( 'userAccount.user', 'childNavigation.{activeIgdiMeasure,currentChild}', function () {

        this.getChildItems();
    }))
})

不推薦觀察者並且@tracked 沒有在服務上工作,所以我不確定如何將 whenUserChanges function 轉換為 Octane。

@tracked 默認情況下不會觀察到 object 的深度變化,因此您需要使用擴展運算符obj = {...obj}來告訴跟蹤 obj 已更改,或者您可以使用ember-deep-tracked ,並調用通過觀察 user.account.status 的 getChildItems 你可以使用ember-render-modifiers提供的渲染鈎子,比如在模板級別did-insert ,例如下面的代碼,

// services/user.js
import Service from '@ember/service';
import {tracked} from '@glimmer/tracking';
import {action} from '@ember/object';

export default class UserService extends Service {
  @tracked account;
  @tracked items=[];

  constructor(...args) {
    super(...args);

    this.account = {
      name: 'myname1',
      status: 'active',
    };
  }

  @action
  changeStatus(status) {
    this.account.status = status;
    this.account = {...this.account}
  }

 @action
  getChildItems() {
      const itemsFromApi = [1,2,3,4,5]
     this.items = [...itemsFromApi];
  }
}

// components/navbar.js
import Component from '@glimmer/component';
import {inject as service } from '@ember/service';
export default class NavbarComponent extends Component {

  @service user;
}



{{!-- components/navbar.hbs --}}
Status:{{this.user.account.status}}

<button type="button" {{on 'click' (fn this.user.changeStatus
  (if (eq this.user.account.status 'active') 'notActive' 'active'))}}>
  Change status
</button>


{{#if (eq this.user.account.status 'active')}}

  <ul {{did-insert this.user.getChildItems}}>
    {{#each this.user.items as |item|}}
      <li>{{item}}</li>
    {{/each}}
  </ul>
{{/if}}




{{!-- templates/application.hbs --}}
{{page-title "Testproject"}}

<Navbar/>

{{outlet}}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM