关于观察者和未消耗的计算属性的混淆

时间:2015-05-26 17:28:15

标签: javascript ember.js

我无法理解下面的陈述,并且不幸地多次读过它:

  

如果您从未获得计算属性,则其观察者将不会触发   如果它的依赖键改变了。你可以想到改变的价值   一个未知的价值到另一个。

     

这通常不会影响应用程序代码,因为已计算   几乎总是在它们的同时观察到性质   牵强。例如,你得到一个计算属性的值,把它   在DOM(或用D3绘制),然后观察它,以便您可以更新   属性改变后的DOM。

这是

的一部分

http://guides.emberjs.com/v1.11.0/object-model/observers/

观察者的一个例子是:

Person = Ember.Object.extend({
  init: function() {
    this.set('salutation', "Mr/Ms");
  },

  salutationDidChange: function() {
    // some side effect of salutation changing
  }.observes('salutation').on('init')
});

这是否意味着如果我不打电话

person.get('salutationDidChange')它将被视为未使用的计算属性,即使salutation发生更改,它也不会执行?

1 个答案:

答案 0 :(得分:1)

他们所说的只是如果你有一个观察者function(){}.observes('salutations')并且你有一个像salutations这样的计算属性function(){}.property('otherValue'),观察者在otherValue时不会被激活}只有在访问.property()时才会返回不同的值。

列出的示例与标题无关。一个更好的例子是:

var auth = Ember.Object.extend({
  isAuthenticated: false,
  currentUser: function(){
     // When foo.get('currentUser') is accessed I will trigger.
     console.log('currentUser')
  }.property('isAuthenticated'),
  doThing: function(){
    // When the value `currentUser` changes, I will trigger.
    console.log('doThing')
  }.observes('currentUser')
});

如果isAuthenticated发生变化,doThing将无法触发,直到您访问currentUser。对isAuthenticated的更改不会通过隐式触发doThing的属性进行级联。