【问题标题】:Ember: Model's property changes not detected in computed propertyEmber:计算属性中未检测到模型的属性更改
【发布时间】:2018-07-12 05:13:26
【问题描述】:

我有 2 个模型。

models/calendar.js

export default Model.extend({
  holidays: hasMany('holiday'),
  date: attr(),
  occasion: attr()
})

models/holiday.js

export default Model.extend({
  calendar: belongsTo('calendar')
})

还有一个组件。

假期/component.js

export default Component.extend({
  init() {
    this._super(...arguments);
    this.store.find('calendar', this.get('calendarId'))
      .then(calendar => this.set('calendar', calendar));
  },

  calendarIsDirty: computed('calendar.holidays.@each.{date,occasion}', function () {
    // This is not executed
  })
})

假期/template.hbs

{{each calendar.holidays as |holiday|}}
  {{input value=holiday.date}}
  {{input value=holiday.occasion}}
{{/each}}

{{#if calendarIsDirty}}
  <button>Save</button>
{{/if}}

我在 UI 中显示假期,当用户编辑假期的日期或场合时,我想做一些事情。但是侦听这些更改的计算属性根本不会执行。请帮我解决这个问题。

我有一个“添加假期”按钮,用于添加用户可以编辑的空假期。当我添加假期时,会执行该计算属性。只有当我对现有假期进行更改时,才会执行计算的属性。

【问题讨论】:

    标签: ember.js ember-data


    【解决方案1】:

    您的问题很简单,假设this.store.findAll('calendar') 返回单个calendar,但它返回calendars 的列表。

    因此:this.set('calendar', calendar) 你将calendar 设置为calendars 的数组。

    接下来你的依赖键 calendar.holidays.@each 是错误的,因为 calendar 是一个数组,因此没有属性 holidays

    如果你想要一个calendar,你应该做一个findIdqueryRecord。如果您想要一组日历,您应该相应地更改您的代码。但是,您需要知道 foo.@each.bar.@each 不是有效的依赖项密钥 - 这是 ember 的限制。你需要解决这个问题。

    【讨论】:

    • 对不起,我就是这么做的。打错问题了。现已更新。
    • 顺便说一句,我以一种 hacky 的方式解决了它。我又添加了一个属性holidaysAsArray: computed('holidays.@each.hasDirtyAttributes', function () { return this.get('holidays').toArray() }) 并将其用于列表并将calendar.holidays.@each.{date,occasion} 更改为calendarIsDirty 中的calendar.holidaysAsArray.@each.{date,occasion}。它现在可以按预期检测更改。
    猜你喜欢
    • 2014-01-07
    • 2014-03-01
    • 2014-10-09
    • 2016-03-07
    • 1970-01-01
    • 2017-04-10
    • 2014-04-06
    • 2018-02-25
    • 1970-01-01
    相关资源
    最近更新 更多