ArrayController按属性和唯一过滤器进行过滤
问题描述:
我有一个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}干扰了这个吗?
答
您应该可以使用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')
});