Ember: Model's property changes not detected in computed property

萝らか妹 提交于 2019-12-11 08:07:44

问题


I have 2 models.

models/calendar.js

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

models/holiday.js

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

And a component.

holidays/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
  })
})

holidays/template.hbs

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

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

I'm displaying the holidays in the UI and when the user edits the date or occasion of the holiday, I want to do something. But the computed property that listens to these changes is not executed at all. Kindly help me with this.

I have an 'Add Holiday' button that adds an empty holiday that the user can edit. When I add a holiday, that computed property is executed. Only when I make changes to an existing holiday, the computed property is not executed.


回答1:


your problem is simple that you assume that this.store.findAll('calendar') returns a single calendar, but it returns a list of calendars.

So with this: this.set('calendar', calendar) you set calendar to an array of calendars.

Next your dependency key calendar.holidays.@each is wrong because calendar is an array and so has no property holidays.

If you want a single calendar you should do a findId or queryRecord. If you want an array of calendars you should change your code accordingly. However you need to know that foo.@each.bar.@each is not a valid dependency key - this is a limitation of ember. you would need to work around this.



来源:https://stackoverflow.com/questions/51297724/ember-models-property-changes-not-detected-in-computed-property

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!