Ember.js 2.3 implement @each.property observer on a HasMany relationship?

£可爱£侵袭症+ 提交于 2019-11-26 21:44:45

问题


Say I have a hasMany relationship Procedure => hasMany Steps, with async:true, and I have a Procedure Component (on the procedure route) called procedure-main, which lists the steps as so:

{{#each steps as |step| }}
 {{step.title}}
{{/each}}

I need to observe a property on each step (say, stepStatus) on change to the stepStatus on any of the steps. In Ember 1.7, I had something like this on the procedure controller:

stepsStatusObserver: function(){
...
}.observes('steps.@each.stepStatus')

This was fired on change of stepStatus on any on the steps, and whatever I had in this function was fired whenever the status changed as well. However, in Ember 2.3, I cannot implement this. I have tried with

stepsStatusObserver: Ember.observer('steps.[].stepStatus', function(){
...
})

but this only fires once when the steps are being listed on the page. When I change the status of one step to a new value, the function is never fired.

How can I replicate this functionality in Ember 2.3?

Note: In my use case, I cannot rely on manually setting off the function inside the observer on the click of a button as it must automatically fire if the stepStatus property was changed on any step.


回答1:


The problem is that steps.[].stepStatus is not a valid dependent key anymore. You should replace it by steps.@each.stepStatus.

Here is a summary of valid and invalid dependent keys in current Ember versions:

  • array - this observes if the array reference itself changes, e.g replacing the entire array with another value or array such as that oldValue !== newValue.
  • array.[] - this observes both when the array itself changes (above) and when the array length changes (functionally equivalent of array.length)
  • array.@each.property - observes both cases above and when property of some of the array's items change
  • array.@each.{prop,anotherProp} - you can also observe multiple properties while specifying only one key. This expands to array.@each.prop and array.@each.anotherProp.
  • array.@each - isn't valid anymore, no trailing @each. Use .[] instead.
  • array.@each.property.property - Also not valid. Note that @each only works one level deep. You cannot use nested forms like todos.@each.owner.name or todos.@each.owner.@each.name.
  • array.[].property - not valid anymore. Use @each form instead.



回答2:


You should still use @each

stepsStatusObserver: Ember.observer('steps.@each.stepStatus', function(){
...
})


来源:https://stackoverflow.com/questions/35689841/ember-js-2-3-implement-each-property-observer-on-a-hasmany-relationship

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