侦听EmberJs辛烷组件中的服务属性更改

kqlmhetl  于 2022-10-20  发布在  其他
关注(0)|答案(1)|浏览(126)

我想知道在服务属性更改后,如何在Emberjs Octane上激发组件中的函数。这里是一个例子,我是如何做到这之前辛烷。
子组件。辛烷之前的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函数转换为Octane。

ubof19bj

ubof19bj1#

@默认情况下,tracked不会观察到对象的深层变化,因此需要使用扩展运算符obj = {...obj}告诉tracked obj已更改,或者可以使用ember-deep-tracked,并通过观察user.account来调用getChildItems。status您可以使用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}}

相关问题