ember data computed property not working on nested association

烂漫一生 提交于 2019-12-10 19:57:42

问题


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

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