Ember Computed Property与Ember Observer

Taz*_*ngo 4 ember.js

我在这里看到的所有先前的问题似乎都没有涵盖何时使用Ember Computed Property和Ember Observer的主题.我知道Computed Property使用以前的属性来帮助生成新属性,并在运行循环中更新.

Person = Ember.Object.extend({
  // these will be supplied by `create`
  firstName: null,
  lastName: null,

  fullName: Ember.computed('firstName', 'lastName', function() {
    return `${this.get('firstName')} ${this.get('lastName')}`;
  })
});
Run Code Online (Sandbox Code Playgroud)

另一方面,观察者在运行循环之外更新,甚至可以观察任何计算属性.它会对任何类型的变化做出反应.

Person = Ember.Object.extend({
  // these will be supplied by `create`
  firstName: null,
  lastName: null,

  fullName: Ember.computed('firstName', 'lastName', function() {
    return `${this.get('firstName')} ${this.get('lastName')}`;
  }),

  fullNameChanged: Ember.observer('fullName', function() {
    // deal with the change
    console.log(`fullName changed to: ${this.get('fullName')}`);
  })
});
Run Code Online (Sandbox Code Playgroud)

然后,Ember文档指出观察者通常过度使用.有人能给出正确使用观察者的更好例子吗?他们还能看到什么,以及错误使用与正确使用的影响是什么?

源代码可以在ember文档中找到:https://guides.emberjs.com/v2.3.0/object-model/observers/

小智 5

Computed Property使用以前的属性来帮助生成新属性,并在运行循环中更新

是的,但是懒惰 - 仅在引用时意味着,并且它们的依赖项更改已使缓存的值无效.

然后,Ember文档指出观察者通常过度使用.

是的,观察者在观察到的属性发生变化时同步发射,即使原因是要重新计算不会被使用的东西.使用观察者应该计算的属性是经典的Ember反模式之一.

我检查了一些我工作过的大型应用程序,发现观察者正在使用某些内容,例如在发生变化时根据需要调用某些第三方库,或者在选择新的UI语言时更改应用程序的语言.