jasongonzales
jasongonzales

Reputation: 1597

Ember-data observe confusion

I have a model like this:

App.Category = DS.Model.extend({
  title: DS.attr('string'),
  items: DS.hasMany('item', {async: true}),
  itemCount: function() {
    return this.get('items').get('length');
  }.property('items')
});

and it seems I cannot use "property" there if I want to have the UI update everytime a user adds or removes items.

From what I can tell I should be using "observes", but when I use that in place of "property" the handlebars {{itemCount}} tag just renders the function itself as a string.

Any help on getting this to render properly is much appreciated.

Upvotes: 0

Views: 55

Answers (2)

Sam Selikoff
Sam Selikoff

Reputation: 12694

Like @florent-blanvillain said, just use Ember.computed.alias. But in the future, when writing computed properties based on arrays, you need to use the @each syntax to get it to respond to changes in property values:

itemCount: function() {
  return this.get('items').filterBy('isSelected');
}.property('[email protected]')

Something like that. See the docs on computed properties for more info.

Upvotes: 1

florent-blanvillain
florent-blanvillain

Reputation: 361

I think you can simply use :

{{items.length}}

in your handlebars template.

There's absolutely no need for an observer, computed properties do updates themselves.

And if you really want a computed property named itemCount, it would be :

itemCount: function() {
  return this.get('items.length');
}.property('items.length')

Or even better :

itemCount: Ember.computed.alias('items.length')

Upvotes: 1

Related Questions