Search code examples
ember.jsember-dataember-cli

How to get the latest active item?


The following returns all active items.

activeItems: Ember.computed('items.@each.status', {
    get() {
        return this.get('items').filter((item) => {
            return item.get('status') === 'active';
        });
    }
})

// Template
{{#each activeItems as |activeItems|}}
  {{activeItem.status}}
{{/each}}

All of above works. Now lets say I want to create a computed property that picks out the last activeItem. I tried:

activeItem: Ember.computed('activeItems', {
  get() {
    return this.get('activeItems').lastObject;
  }
}),

// Template
{{activeItem.status}} <-- returns nothing

Why is this and how can I get it to work?


Solution

  • I see 2 problems:

    1. Your computed property has the incorrect dependent key. By only relying on activeItems, the problem will only update when the activeItems property returns a new object, not when the contents are updated. You should be watching activeItems.lastObject.
    2. lastObject is a computed property, which means you might not be able to access it without using Ember's get() function.

    Try this:

    activeItem: Ember.computed('activeItems.lastObject', {
        get() {
            return this.get('activeItems.lastObject');
        }
    })
    

    Or, for the shorthand:

    activeItem: Ember.computed.reads('activeItems.lastObject')