gpt4 book ai didi

ember.js - Ember JS : Unable to get the length of an hasMany array two levels down

转载 作者:行者123 更新时间:2023-12-02 21:54:20 25 4
gpt4 key购买 nike

我正在尝试创建一个计算属性来获取所有页面的长度总和。

但是我不知道如何访问一个 child ,这样我就可以得到那个 child 的 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')
})

最佳答案

以下是如何访问跨页数组中的第一个对象的示例:

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

但我猜你想在这里获取总页数。 因此,这是一个如何迭代跨页并对页数求和的示例:

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

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

关于ember.js - Ember JS : Unable to get the length of an hasMany array two levels down,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15951223/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com