使用@each可以观察数组中的数组吗?
问题描述:
我有一个包含“事物”数组的控制器。在每一件事情中,都有一系列“亚树”。我想创建一个计算属性,其中包含所有东西的所有子项(扁平数组的子项)。使用@each可以观察数组中的数组吗?
我的计算属性取决于[email protected]
。我发现,如果我设置subthings
属性的东西,我的计算属性更新。但是,如果我呼叫pushObjects
向我的现有的subthings
数组添加新数据,我的计算属性不会更新。
我创建了一个jsfiddle来演示。代码如下:
App = Em.Application.create({});
App.controller = Em.Object.create({
things: [
Em.Object.create({subthings:[]}),
Em.Object.create({subthings:[]}),
Em.Object.create({subthings:[]})
],
allSubThings : function() {
var things = this.get('things');
var results = [];
things.forEach(function(thing) {
results.pushObjects(thing.get('subthings'));
});
return results;
}.property('[email protected]').cacheable()
});
setTimeout(function() {
var things = App.controller.get('things');
// This works:
things.objectAt(0).set('subthings',[1,2,3]);
}, 1000);
setTimeout(function() {
var things = App.controller.get('things');
// This does not:
things.objectAt(1).get('subthings').pushObjects([1,2,3]);
}, 2000);
谢谢!
行之有效,谢谢!也许我不太明白@each在这里做什么。看来你的解决方案是观察“子集”数组中每个元素的长度属性,而不是子集数组本身的长度。 – rharper 2012-02-21 16:41:59
来自Ember文档:http://emberjs.com/guides/object-model/computed-properties-and-aggregate-data/“请注意@each只能深入一层,不能使用像todos这样的嵌套表单。 .owner.name或todos。@ each.owner。@ each.name – 2014-03-18 19:54:55