【问题标题】:Confusion About Observers and Unconsumed Computed Properties关于观察者和未使用的计算属性的困惑
【发布时间】:2015-08-08 12:21:39
【问题描述】:

我无法理解下面的陈述,很遗憾我已经阅读了很多遍:

如果你从来没有得到一个计算属性,它的观察者甚至不会触发 如果它的依赖键发生变化。你可以认为值从 一个未知的值。

这通常不会影响应用程序代码,因为计算 几乎总是同时观察到属性 获取。例如,你得到一个计算属性的值,把它 在 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 发生变化也不会执行?

【问题讨论】:

  • 你为什么要问这个?如果两种方式都运行代码,看看你的观察者函数是否被调用。

标签: javascript ember.js


【解决方案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 的属性进行级联。

【讨论】:

    猜你喜欢
    • 2016-04-22
    • 2020-11-20
    • 1970-01-01
    • 1970-01-01
    • 2017-09-02
    • 2017-04-25
    • 2015-04-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多