应该触发并进行API调用的计算属性根本不会触发(Ember 2.8)

时间:2016-11-18 10:24:54

标签: ember.js

我有两个计算属性,应该在month属性更改后触发。然而,其中只有一个发射,而另一个没发射。

classesForMonth在初始化时触发一次(第一次设置为month时),之后不会触发。

我认为这可能是由classesForMonth.content语法引起的,我必须在模板中使用它来查询在查询DS后从Promise收到的Object。

请帮助我走上正轨。

  classesForMonth: function() {
    console.log('hi im querying store') // doesn't fire on month change
    return this.get('store').query('class', {
      month: this.get('month') + 1,
    });
  }.property('month'),

  formattedMonth: function(){
    console.log('hi im formatting month') // does fire on month change
    return moment.months()[this.get('month')]
  }.property('month')

2 个答案:

答案 0 :(得分:2)

实际上这个计算属性看起来非常好。我已经构建了一个twiddle来表明它正在运作。

可能你的问题是你没有正确地消费它。有几点需要注意:

  • 计算属性仅在消耗时执行。如果你在模板中显示它,或者.get()则显示它,它就不会计算。
  • store.query会返回DS.PromiseArray
  • .content属性不是promises的默认属性。它是DS.PromiseArrayDS.PromiseObject专用的私有API。好吧,因为它的私人你真的不应该使用它
  • 在计算属性中返回普通的Promise是不行的。退回PromiseArrayPromiseObjet即可。
  • 如果您有PromiseObjectPromiseArray,则可以像模板中的普通对象一样使用它。忽略承诺的东西。
  • store.query应返回多条记录。如果您只想使用一次store.queryRecord

所以基本上如果你只做像

这样的事情
{{#each classesForMonth as |class|}}
  ...
{{/each}}

这会有效!

答案 1 :(得分:0)

既然你是从某个地方查询的,并且在某些情况下在计算属性中返回一个promise是不明智的,那么observers最好这样:

classesForMonth: null
changeClasses: Ember.observer('month', function() {
    this.set('classesForMonth', this.get('store').query('class', {
      month: this.get('month') + 1,
    }));

    // or maybe better to avoid calling `.content` in you template
    this.get('store').query('class', {
      month: this.get('month') + 1,
    })).then(classes => this.set('classesForMonth', classes));
})