问题
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 thatoldValue !== newValue.array.[]- this observes both when the array itself changes (above) and when the array length changes (functionally equivalent ofarray.length)array.@each.property- observes both cases above and whenpropertyof some of the array's items changearray.@each.{prop,anotherProp}- you can also observe multiple properties while specifying only one key. This expands toarray.@each.propandarray.@each.anotherProp.array.@each- isn't valid anymore, no trailing@each. Use.[]instead.array.@each.property.property- Also not valid. Note that@eachonly works one level deep. You cannot use nested forms liketodos.@each.owner.nameortodos.@each.owner.@each.name.array.[].property- not valid anymore. Use@eachform 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