问题描述
我的应用程序具有以下模型:
My application has the following models:
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?
How can I calculate the sum of all App.User.tweetsUnread and make it automatically update App.List.tweetsUnread?
推荐答案
以下应该做到.使用reduce可能有更简洁的解决方案,但我自己从未使用过:-)
The following should do it. There might be an more concise solution using reduce, but i have never used it myself :-)
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 的更优雅的解决方案.我从未使用过它,也没有经过测试,但我非常有信心这应该有效:
Update: This is a more elegant solution using reduce. I have never used it and this isn't tested but i am quite confident that this should work:
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 已经改变了它们的位置.所以这里是正确版本的代码:
In Ember 1.1 the API for reduce has changed! Thx @joelcox for the hint, that the parameters initialValue and callback have changed their position. So here the correct version of the code:
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]")
});
这篇关于Ember.js:计算所有子模型的属性总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!