1

I'm somewhat at a loss with what should be easily achieved with Ember computed properties. I'm using https://github.com/funkensturm/ember-local-storage to manage a local favorites list.

Now I have a component which should display the object's status, along with the infamous "star" button for toggling the favorite state.

My component code goes as follows:

import Ember from 'ember';
import FavoritesLocal from 'my-app/models/favorites-local';

export default Ember.Component.extend({

    storedFavorites: FavoritesLocal.create(),

    isFavorite: Ember.computed('storedFavorites', function () {
        return this.get('storedFavorites').contains(this.model.get('id'));
    }),

    actions: {
        toggleFavorite() {
            if(this.get('isFavorite')) {
                this.get('storedFavorites').removeObject(this.model.get('id'));
            } else {
                this.get('storedFavorites').addObject(this.model.get('id'));
            }
        }
    }

});

The template contains a

{{#if isFavorite}}
  <a {{action 'toggleFavorite'}} href="#"></a>
{{else}}
  <a {{action 'toggleFavorite'}} href="#"></a><
{{/if}}

The model for the local-storage is simply

import StorageArray from 'ember-local-storage/local/array'

export default StorageArray.extend({
    storageKey: 'myFavorites'  
});

Now, of course I want the component to update if the button is clicked.

My specific question is concerning WHAT exactly the computed property should be observing. A crude attempt for listening for changes in the storedFavorites property (see above) failed.

Clearly, I could send an action up to the controller and let it handle it and update the template, but that seems a little overdo? What am I missing?

Thanks!

Julian Rubisch
  • 547
  • 7
  • 21

1 Answers1

1

I haven't worked with this yet, but my guess is that you want to observe storedFavorites.length.

Remi Smirra
  • 2,499
  • 1
  • 14
  • 15
  • thanks! I was already suspecting something like this, although I wasn't sure how to query it in ComputerProperty-Syntax. Simply `Ember.computed('storedFavorites.length', ...)` did it. – Julian Rubisch Jan 11 '16 at 15:22
  • a more Ember-way would be `'storedFavorites.[]`, see https://guides.emberjs.com/v3.3.0/object-model/computed-properties-and-aggregate-data/ – chaimann Nov 18 '21 at 15:58