2
votes

I'm having a bit of a problem keeping my Array fully in sync with the template, the ArrayController is keeping an eye on objects being pushed, removed and updated. However, the ArrayController is filtering the results, and when one of the objects changes and it's new properties may end up leaving it out of the filter, it's not actually being removed.

See the code below, for the sake of simplifying things content is set to an array of objects, but in my application it's actually Ember.A([Ember.Object, Ember.Object]) and so on, the underlying array is mutable, it's changing all the time along with it's objects.

App.TabController = Ember.ArrayController.extend({
    content: [
        {id: 1, key: 'unique'},
        {id: 2, key: 'unique'},
        {id: 3, key: 'non-unique'},
    ],

    filteredContent: function() {
        var content = this.get('content');

        return this.filter(function(item, idx, en) {
            return (item.key == 'unique');
        });
    }.observes('content.length').property('content'),
});

The above code works absolutely fine for keeping the third object out of the template, because it's key hasn't matched the value of unique. However say the object with id equal to 3 gets updated, and it's key changes to unique, it's not pushed into the template - which I would like it to be, I've tried a few solutions but to no avail.

I'll also note that if any new objects come with the correct key then they are inserted into the template, and if they are removed they are also removed, also any values in the object that is displayed in the template are updated when the object changes, so I know the ArrayController is doing it's job, it's just not re-filtering the results.

Is this even possible without forcing a full re-render or some other sorcery?

2

2 Answers

2
votes

I'd use the filterBy computed property macro, kind of like this:

App.TabController = Ember.ArrayController.extend({
  filteredContent: Ember.computed.filterBy('content', 'key', 'unique')
});
1
votes

For avoiding recalculation of the array and improve performance, use Ember.arrayComputed. Here's how to use it with your case:

App.TabController = Ember.ArrayController.extend({
  filteredContent: Ember.arrayComputed("content.[]", {
    initialValue: [],
    addedItem: function(accum, item) {
      if (item.key == 'unique') {
        accum.pushObject(item);
      }
      return accum;
    },
    removedItem: function(accum, item) {
      accum.removeObject(item);
      return accum;
    }
  })
});