2014-09-26 76 views
1

我有一個Foo對象的ArrayController,它們與bar對象之間的關係具有「bar」屬性。ArrayController按屬性和唯一過濾器進行過濾

var Foo = DS.Model.extend({ 
    bar : DS.belongsTo('bar', {async:true}) 
}); 

var Bar = DS.Model.extend({ 
    foos : DS.hasMany('foo', {async:true}) 
}); 

我有一個在Foos數組中找到的唯一條的計算屬性(一些Foos共享同一個條)。

var FooArray = Ember.ArrayController.extend({ 

    bars: function(){ 
     return this.get('content').getEach('bar'); 
    }.property("@each.bar"), 

    unique_bars : function(){ 
     return Ember.A(_.uniq(this.get('bars'), function(c){return c.get('id');})); 
    }.property("bars"), 

}); 

Underscore.uniq()在那裏使用,因爲Ember.Array.uniq不讓你指定比較器。有Ember.Comparable mixin,但是它會爲整個類定義一個唯一性比較器,這對我並不感興趣,因爲我希望根據不同環境下的某些不同屬性找到唯一性。

尋找獨特子屬性的方法可能需要改進。無論如何如預期上面的代碼不起作用:

foo_array.get('unique_bars') 

得到包含1條數組,雖然應該有20

Ember.A(_.uniq(foo_array.get('bars'), function(c){return c.get('id');})) 

的作品就好了。 20個酒吧,從一個更大的數字獨特的設置。

我相信'unique_bars'屬性只有在第一個Foo添加到foo_array後纔會評估一次。

那麼觀察者表達式有什麼問題?或者{async:true}干擾了這個嗎?

回答

2

您應該可以使用getEach來獲取條形碼和ID,然後在ids集合上使用uniq。然後你可以看ID各條

var FooArray = Ember.ArrayController.extend({ 
    bars: function(){ 
     return this.getEach('bar'); 
    }.property("@each.bar"), 

    bar_ids : function(){ 
     return this.get('bars').getEach('id'); 
    }.property("[email protected]"), 

    unique_ids: Em.computed.uniq('bar_ids') 
}); 

例如在:http://emberjs.jsbin.com/OxIDiVU/1102/edit