2012-09-04 154 views
1

我有一個小提琴http://jsfiddle.net/kristaps_petersons/9wteJ/2/它加載3個對象,並在視圖中顯示它們。數據顯示正常,但在展示之前我無法對其進行過濾。 這Ember.Controller數組內容過濾

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')這是爲什麼?

回答

2

您試圖替換controller.content,同時也綁定到它。您需要定義另一個屬性,例如filteredContent並將其綁定到controller.content。看看Ember.SortableMixin如何爲定義了sortProperties變量的控制器計算變量arrangedContent。使用該方法作爲模板,我會這樣實現它:

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以顯示過濾的數據。然後原始內容和過濾的內容都可用。

+0

我改變了你說的代碼,但它仍然沒有進入循環。檢出小提琴 http://jsfiddle.net/kristaps_petersons/9wteJ/11/ 我添加了兩個console.log行 'console.log('BEFORE應該記錄這至少3倍')' 'console.log('AFTER應該至少記錄這3行')' 它會像以前一樣打印這些行,但不會進入循環。儘管所有節點都返回 – Kristaps

+0

添加'cacheable()'也沒有解決 – Kristaps

+0

我最近一直在爲Ember ArrayController進行實時篩選。它建立在這個例子上。請參閱http://jsbin.com/UvePomO/4/edit?html,js輸出 – adroitec

0

好吧,我得到它的工作,但它感覺有點奇怪。首先我感動的方法來控制類,並改變了它看起來像這樣:

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('[email protected]'),它正在工作。小提琴:http://jsfiddle.net/kristaps_petersons/9wteJ/21/。我想,這個臨時文件首先會創建一個到controller.content的綁定,並且由於內容本身不會再發生變化,所以不會再次通知此方法,而是在數據變爲可用時拉取數據。