我的应用程序具有以下模型:
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?
最佳答案
下面应该这样做。使用reduce可能会有更简洁的解决方案,但我自己从未使用过它:-)
App.List = DS.Model.extend({
name: DS.attr('string'),
users: DS.hasMany('App.User'),
tweetsUnread: function(){
var users = this.get("users");
var ret = 0;
users.forEach(function(user){
ret += users.get("tweetsUnread");
});
return ret;
}.property("[email protected]")
});
更新:这是一个使用reduce的更优雅的解决方案。我从未使用过它,也没有经过测试,但是我很有信心这应该起作用:
App.List = DS.Model.extend({
name: DS.attr('string'),
users: DS.hasMany('App.User'),
tweetsUnread: function(){
var users = this.get("users");
return users.reduce(0, function(previousValue, user){
return previousValue + users.get("tweetsUnread");
});
}.property("[email protected]")
});
在Ember 1.1中,reduce的API已更改! Thx @joelcox提示,参数initialValue和callback已更改其位置。所以这里是正确的代码版本:
App.List = DS.Model.extend({
name: DS.attr('string'),
users: DS.hasMany('App.User'),
tweetsUnread: function(){
var users = this.get("users");
return users.reduce(function(previousValue, user){
return previousValue + user.get("tweetsUnread");
}, 0);
}.property("[email protected]")
});
关于model - Ember.js:计算所有子模型的属性总和,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/15933633/