Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EmberJS: Unable to get the length of an hasMany array two levels down

Im trying to create a computed property to get me the sum of the length of all pages.

But i cannot figure out how to access a child so i can get the childs of that child.

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')
})
like image 339
Snidd Avatar asked Apr 11 '13 14:04

Snidd


1 Answers

Here is an example of how you get access to the first object in the array of spreads:

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')
});

But i guess you want to get the total number of pages here. So, here is an example how to iterate the spreads and sum the number of pages:

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('[email protected]')
});

Note: Look at the property dependency i declared via property. Since the ComputedProperty depend on those paths, you need to declare them there.

like image 130
mavilein Avatar answered Nov 06 '22 15:11

mavilein