Reputation: 12861
I have an ArrayController for Foo objects, which have a "bar" attribute for their relationship with Bar objects.
var Foo = DS.Model.extend({
bar : DS.belongsTo('bar', {async:true})
});
var Bar = DS.Model.extend({
foos : DS.hasMany('foo', {async:true})
});
I have a computed property for the unique bars found in the array of Foos (some Foos share the same Bar in common).
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() is used there since Ember.Array.uniq doesn't let you specify the comparator. There is the Ember.Comparable mixin, but that would define a single uniqueness comparator for the entire class, which doesn't interest me because I will want to find uniqueness based on some different properties in different circumstances.
The approach to finding unique sub-properties may need improvement. At any rate the above code does not work as expected:
foo_array.get('unique_bars')
Yields an array containing 1 Bar, although there should be 20.
Ember.A(_.uniq(foo_array.get('bars'), function(c){return c.get('id');}))
works just fine. 20 bars, the unique set from a larger number.
I believe the 'unique_bars' property evaluates only once after the first Foo is added to the foo_array.
So what could be wrong with the observer expressions? Or does {async:true} interfere with this?
Upvotes: 1
Views: 703
Reputation: 47367
You should be able to use getEach to get both the bars, and the ids, and then use uniq on the ids collection. Then you can watch the id on each bar
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')
});
Example: http://emberjs.jsbin.com/OxIDiVU/1102/edit
Upvotes: 2