我的应用程序具有以下模型:
App.Store = DS.Store.extend({
revision: 11,
adapter: 'DS.FixtureAdapter'
});
App.List = DS.Model.extend({
name: DS.attr('string'),
users: DS.hasMany('App.User'),
tweetsUnread: function(){
/////////////////////////////////////////
// Code to dynamically calculate the sum
// of tweetsUnread property of all
// App.User that are related to this list
/////////////////////////////////////////
}
});
App.User = DS.Model.extend({
screenName: DS.attr('string'),
tweets: DS.hasMany('App.Tweet'),
tweetsUnread: function(){
// TODO: check if this is the correct way to do it
return this.get('tweets').get('length');
}.property('tweets.@each'),
list: DS.belongsTo('App.List')
});
App.Tweet = DS.Model.extend({
text: DS.attr('string'),
user: DS.belongsTo('App.User')
});
如何计算所有 App.User.tweetsUnread 的总和并使其自动更新 App.List.tweetsUnread?
最佳答案
另一种选择是使用 Ember.computed.sum
见 here
App.List = DS.Model.extend({
name: DS.attr('string'),
users: DS.hasMany('App.User'),
tweetsUnread: Ember.computed.mapBy('users', 'tweetsUnread'),
totalTweetsUnread: Ember.computed.sum('tweetsUnread')
});
关于model - Ember.js:计算所有子模型的属性总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15933633/