【问题标题】:Computed property that should fire and make an API call doesn't fire at all (Ember 2.8)应该触发并进行 API 调用的计算属性根本不会触发(Ember 2.8)
【发布时间】:2017-04-02 03:49:30
【问题描述】:

我有两个计算属性应该在month 属性更改后触发。但是,其中只有一个会着火,而另一个不会。

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

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

请帮助我走上正轨。

  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')

【问题讨论】:

  • 您使用的是什么版本的 ember?
  • 我使用的是 Ember 2.8。
  • 您在模板中使用 formattedMonth 吗?
  • 是的,我在我的模板中都使用了这两种方法。 formattedMonth 正确呈现和更改。
  • 附带说明:您应该改用Ember.computed('month', function() {...}) 表示法。是的,我认为你在模板的正确轨道上。您能否确认,返回this.get('store').query 成功完成?你注入商店了吗?我假设您的模板中可能有 classesForMonth.content 之类的东西?这可能不会调用您正在寻找的绑定逻辑

标签: ember.js


【解决方案1】:

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

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

  • 计算属性仅在使用时才会执行。如果您在模板中显示或 .get() 显示它,则它不会计算。
  • store.query 返回 DS.PromiseArray
  • .content 属性不是 Promise 的默认值。它是DS.PromiseArrayDS.PromiseObject 独有的私有API。好吧,既然它是私有的,你真的不应该使用它
  • 在计算属性中返回一个普通的 Promise 是不行的。返回 PromiseArrayPromiseObjet 即可。
  • 如果您有PromiseObjectPromiseArray,您可以像模板中的普通对象一样使用它。忽略 Promise 的东西。
  • store.query 应该返回多条记录。如果您只想要一个,请使用store.queryRecord

所以基本上如果你只是做类似的事情

{{#each classesForMonth as |class|}}
  ...
{{/each}}

这会起作用的!

【讨论】:

    【解决方案2】:

    由于您是从某个地方进行查询,并且在某些情况下,在计算属性中返回一个 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));
    })
    

    【讨论】:

    • 介意解释在模板中返回承诺并调用.content 有什么问题吗?到目前为止,我还没有遇到过这个问题(除了我自己的愚蠢造成的这个问题)。
    • 它不是“余烬之路”;)。如果您只想显示内容,它正在工作。但是,您可能会失去约束力,例如从模板中设置内容时。另外,像你这样的错误正在发生。如果您想实际将其用作计算属性。可能想看看@kumkanillams 的答案。
    • @Senthe 因为.content 上的PromiseProxyMixin 是私有的。这应该是足够的理由。但是 is 保存返回 PromiseProxyMixin 并在模板中使用 property.someProperty。只是不要使用content
    • @Remi 对不起,但我认为观察者几乎永远不是解决方案。
    猜你喜欢
    • 1970-01-01
    • 2014-07-22
    • 1970-01-01
    • 2017-07-22
    • 1970-01-01
    • 1970-01-01
    • 2018-12-29
    • 1970-01-01
    相关资源
    最近更新 更多