我有一个fiddle http://jsfiddle.net/kristaps_petersons/9wteJ/2/,它加载3个对象,并在视图中显示它们。数据可以正常显示,但在显示之前我无法对其进行过滤。这
nodes: function(){
this.get('controller.content').filter(function(item, idx, en){
console.log('should log this atleast 3x')
})
return this.get('controller.content')
}.property('controller.content')
方法被调用时,模板迭代数组的值,但它从来没有进入循环和打印console.log('should log this atleast 3x')
为什么?
发布于 2012-09-05 12:20:48
您正在尝试替换controller.content
,同时还绑定到它。您需要定义另一个属性,如filteredContent
并将其绑定到controller.content
。看一看Ember.SortableMixin如何为定义了arrangedContent
变量的控制器计算变量sortProperties
。使用该方法作为模板,我将像这样实现它:
filteredContent: Ember.computed('content', function() {
var content = this.get('content');
return this.filter(function(item, idx, en) {
console.log('should log this atleast 3x');
});
}).cacheable()
这应该在控制器中实现,而不是在视图中。控制器是数据操作、计算属性和绑定的位置。
然后将视图布局绑定到filteredContent
而不是content
,以显示过滤后的数据。那么原始内容和过滤后的内容都是可用的。
发布于 2012-09-05 16:18:55
好的,我让它工作了,但是感觉有点奇怪。首先,我将方法移动到Controller类,并将其更改为如下所示:
nodes: function(){
console.log('BEFORE should log this atleast 3x', this.get('content.length'))
this.get('content').forEach(function(item, idx, en){
console.log('should log this atleast 3x')
})
console.log('AFTER should log this atleast 3x', this.get('content.length'))
return this.get('content')
}.property('content').cacheable()
因为它应该与buuda的recomedation相同,因为我从文档中了解到.poperty()
与Ember.computed
是相同的。由于它仍然不起作用,所以我将.property('content')
更改为.property('content.@each')
,并且它起作用了。小提琴:http://jsfiddle.net/kristaps_petersons/9wteJ/21/。我猜,tempate首先创建一个到controller.content
的绑定,当内容本身不变时,不会再次通知此方法,相反,模板会在数据可用时提取数据。
https://stackoverflow.com/questions/12264292
复制相似问题