For loop 如何在计算属性中使用嵌套对象属性?
我很难理解在嵌套对象模型中调用子对象属性并使用它们计算新属性的正确方法。以下是我目前正在尝试的:For loop 如何在计算属性中使用嵌套对象属性?,for-loop,ember.js,For Loop,Ember.js,我很难理解在嵌套对象模型中调用子对象属性并使用它们计算新属性的正确方法。以下是我目前正在尝试的: Monitor.ProcessController = Ember.ObjectController.extend({ nbUsers: function() { var total = 0; this.get('containers').then(function(containers) { containers.forEach(function(con
Monitor.ProcessController = Ember.ObjectController.extend({
nbUsers: function() {
var total = 0;
this.get('containers').then(function(containers) {
containers.forEach(function(container, index){
total += container.get('nbUsers');
});
});
return total;
}.property('containers.@each.nbUsers')
});
Monitor.ContainerController = Ember.ObjectController.extend();
Monitor.Process = DS.Model.extend({
containers: DS.hasMany('container', {async : true}),
name: DS.attr('string')
});
Monitor.Container = DS.Model.extend({
process: DS.belongsTo('process'),
name: DS.attr('string'),
nbUsers: DS.attr('integer')
});
// Test data
Monitor.Process.FIXTURES = [
{
id: 1,
name: 'Mumble',
containers: [1,2]
},
{
id: 2,
name: 'EVE',
containers: [3]
}
];
Monitor.Container.FIXTURES = [
{
id: 1,
name: 'First',
process: 1,
nbUsers: 1
},
{
id: 2,
name: 'Second',
process: 1,
nbUsers: 1
},
{
id: 3,
name: 'Unique',
process: 2,
nbUsers: 1
}
];
因此,一个进程有多个子容器,我想根据容器数据动态计算每个进程的总用户数。听起来微不足道,显然不是
{{nbUsers}}}不断返回“0”。
有没有关于我做错了什么的指针?您的属性是异步的,因此您在更新total之前返回0,并且由于它不是要传递回的引用,因此它不会更新已经返回的值。因此,属性total会更新,但不会更新返回到计算属性的值
Monitor.ProcessController = Ember.ObjectController.extend({
nbUsers: 0,
nbUsersWatcher: function() {
var self = this;
this.get('containers').then(function(containers) {
var total = 0;
containers.forEach(function(container, index){
total += container.get('nbUsers');
});
self.set('nbUsers', total);
});
}.observes('containers.@each.nbUsers')
});
更改它的最简单方法是将它设置为观察者,并让它更新属性
Monitor.ProcessController = Ember.ObjectController.extend({
nbUsers: 0,
nbUsersWatcher: function() {
var self = this;
this.get('containers').then(function(containers) {
var total = 0;
containers.forEach(function(container, index){
total += container.get('nbUsers');
});
self.set('nbUsers', total);
});
}.observes('containers.@each.nbUsers')
});
您可能也可以使用computed,但在我告诉您这是可能的之前,我必须先进行测试。我真的需要让它异步吗?我感到惊讶的是,像聚合来自儿童的数据这样琐碎的事情需要在Ember中使用如此复杂的函数?