ancoanco
ancoanco

Reputation: 220

Ember computed properly not firing on property change

I'm having a weird issue where a computed property isn't firing when it's dependent properties change.

Computed Property and Actions

answers: computed('variant.questionAnswers.[]', function() {
  return get(this, 'variant.questionAnswers').sortBy('position');
}),

...

actions: {
  reorderItems(answerModels) {
    answerModels.forEach(function(item, index) {
      set(item, 'position', index + 1);
    });
  }
}

The answerModels in the action is an array of all the answers, and setting the position works properly in that action. I can see the position changing in the ember inspector as well as when I inspect the individual models.

However, it does not update the view order because the answers computed property does not get fired.

I've tried changing the dependent property to variant.questionAnswers, [email protected], variant.questionAnswers.[], but nothing seem to fire when I change the position in the action.

How I got around it was add a timeHack attribute that makes it work, but obviously is not ideal...

timeHack: null,

answers: computed('timeHack', 'variant.questionAnswers.[]', function() {
  return get(this, 'variant.questionAnswers').sortBy('position');
}),

actions: {
  reorderItems(answerModels) {
    answerModels.forEach(function(item, index) {
      set(item, 'position', index + 1);
    });
    set(this, 'timeHack', new Date());
  }
}

Any thoughts on how to get this to work?

Upvotes: 1

Views: 290

Answers (1)

Grapho
Grapho

Reputation: 1654

[email protected] is the correct dependent key for the computed property you have created. The reason i say that is because position is the actual value that you are changing in each array item.. so it is not sufficient to observe the array items alone.

the part that is not clear to me.. in your question: is answerModels array in the action, in fact, the same variant.questionAnswers array you are comparing in the computed property?

When i look closer at your action.. it does not look like your code would do anything to change the overall sort order? you are increasing all the items position by +1, so maybe that is why you dont visually see a change in the sort order.

Upvotes: 2

Related Questions