Search code examples
ember.jscomputed-propertiesember-local-storage

Ember component: computed property observing local storage array


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!


Solution

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