简体   繁体   中英

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.

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')

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('items.@each.isSelected')

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM