Search code examples
ember.jshandlebars.jsember-cli

Can't observe computed property


I've got a controller sorting posts first, then there's a filter applied to them. Sadly when I use {{#each post in filteredPosts}} in my template they don't live update.

How can I achieve the sorting on multiple columns (in different directions), then the filtering AND still have new and deleted posts appear in the list live?

import Ember from 'ember';

export default Ember.ArrayController.extend({
  sortProperties: ['isPublished:asc', 'createdAt:desc'],
  sortedPosts: Ember.computed.sort('model', 'sortProperties'),
  filterPost: '',

  filteredPosts: function() {
    var filterText = this.get('filterPost').toLowerCase()
    return this.get('sortedPosts').filter(function(post){
      return post.get('title').toLowerCase().indexOf(filterText) > -1
    })
  }.observes('sortedPosts').property('filterPost'),

});

Solution

  • Your computed property has two things wrong with it.

    1. You're using both .observes() and .property(). You only need .property(). .observes() is for when you want to make side-effect changes when a property updates.
    2. You're only watching sortedPosts, which means that your property will only recalculate when the sortedPosts iterable itself changes, not when any of the content changes. Because you're filtering by the title property, you should be watching that on every instance. You can read more about this here.

    Your computed property should look something like this:

    filteredPosts: function() {
        ...
    }.property('sortedPosts.@each.title', 'filterPost')