且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Ember.js:计算所有子模型的属性的总和

更新时间:2023-02-10 13:30:06

以下应该做到。可能有一个更简洁的解决方案,使用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("users.@each.tweetsUnread")
});

更新:这是使用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("users.@each.tweetsUnread")
});

在Ember 1.1中,用于reduce的API已更改! Thx @joelcox for提示,参数initialValue和回调已经改变了他们的位置。所以这里代码的正确版本:

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("users.@each.tweetsUnread")
});