EmberJS:无法将hasMany数组的长度降低两级

Sni*_*idd 7 has-many ember.js

我试图创建一个计算属性,以获得所有页面的长度总和.

但我无法弄清楚如何接触一个孩子,所以我可以得到那个孩子的孩子.

App.Document = DS.Model.extend({
    name: DS.attr('string'),
    spreads: DS.hasMany('App.Spread'),

    pagesCount: function() {
                // Here is where i go wrong, i can get the length of spreads, but not access a spread to get the page length.
                var spreadsLength = this.get('spreads.length');
                var firstSpread = this.get('spreads')[0];
                return firstSpread.get('pages.length');
    }.property('spreads')
});

App.Spread = DS.Model.extend({
    document: DS.belongsTo('App.Document'),
    pages: DS.hasMany('App.Page')
})

App.Page = DS.Model.extend({
    spread: DS.belongsTo('App.Spread'),
    page_name: DS.attr('string'),
    page_items: DS.hasMany('DS.PageItem')
})
Run Code Online (Sandbox Code Playgroud)

mav*_*ein 11

以下是如何访问点差数组中第一个对象示例:

App.Document = DS.Model.extend({
    name: DS.attr('string'),
    spreads: DS.hasMany('App.Spread'),

    pagesCount: function() {
        // Here is where i go wrong, i can get the length of spreads, but not access a spread to get the page length.
        var spreadsLength = this.get('spreads.length');

        var firstSpread = this.get('spreads').objectAt(0);
        // var firstSpread = this.get('spreads.firstObject'); // elegant way to first Object

        return firstSpread.get('pages.length');
    }.property('spreads.firstObject.pages.length')
});
Run Code Online (Sandbox Code Playgroud)

但我想你想在这里获得总页数.那么,这里是一个如何迭代点差并总结页数的示例:

App.Document = DS.Model.extend({
    name: DS.attr('string'),
    spreads: DS.hasMany('App.Spread'),

    pagesCount: function() {
        // Here is where i go wrong, i can get the length of spreads, but not access a spread to get the page length.
        var spreadsLength = this.get('spreads.length');
        var ret = 0;
        this.get("spreads").forEach(function(spread)){
            ret += spread.get('pages.length');
        }
        return ret;
    }.property('spreads.@each.pages.length')
});
Run Code Online (Sandbox Code Playgroud)

注意:查看我声明的属性依赖项property.由于ComputedProperty依赖于这些路径,因此您需要在那里声明它们.