问题
I have a simple datamodel:
a Leg, has many Players, who have many Turns:
App.Store = DS.Store.extend({
revision: 11,
adapter: 'DS.FixtureAdapter'
});
App.Leg = DS.Model.extend({
players: DS.hasMany('App.Player'),
turnCount: function() {
var i = 0;
this.get('players').forEach(function(p) {
i+= p.get('turns.length');
});
return i;
}.property('players.@each.turns.length')
});
App.Player = DS.Model.extend({
leg: DS.belongsTo('App.Leg'),
turns: DS.hasMany('App.Turn')
});
App.Turn = DS.Model.extend({
player: DS.belongsTo('App.Player')
});
The computed property turnCount
doesn't automatically get updated when I create a new Turn, but it should, right?
/*
* do this on the console to verify
*/
var leg = App.Leg.createRecord();
var player = leg.get('players').createRecord();
leg.get('turnCount');
// => 0
player.get('turns').createRecord();
leg.get('turnCount')
// => 0
UPDATE
It seems that if you stick to one layer of nesting things just work. So:
.property('players.@each.someProperty')
works, as long as that someProperty is not an Enumerable.
回答1:
Try this:
.property('players.@each.turns.@each')
You could also use the reduce method to calculate totals:
turnCount: function() {
return this.get('players').reduce(function(value, player) {
return value + player.get('turns.length');
}, 0);
}.property('players.@each.turns.@each')
来源:https://stackoverflow.com/questions/14860352/ember-data-computed-property-not-working-on-nested-association