EmberJS:无法获得hasMany数组的长度两级 [英] EmberJS: Unable to get the length of an hasMany array two levels down
本文介绍了EmberJS:无法获得hasMany数组的长度两级的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图创建一个计算属性来获取所有页面的长度的总和。
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')
})
推荐答案
下面是一个示例,说明如何访问spread数组中的第一个对象:
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('spreads.@each.pages.length')
});
注意:看看我通过属性
。由于ComputedProperty依赖于这些路径,您需要在那里声明它们。
Note: Look at the property dependency i declared via property
. Since the ComputedProperty depend on those paths, you need to declare them there.
这篇关于EmberJS:无法获得hasMany数组的长度两级的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文