我想观察模型每个实例的变化。鉴于这个小例子,当一个类别的项目数量发生变化时,百分比值应该为每个其他类别发生变化。在此示例中,它不会更新 percentValue:
App.Category = DS.Model.extend({
name: DS.attr('string'),
items: DS.hasMany('App.Item'),
percentValue: function() {
var total_items = App.Item.all().get('length')
var category_items = this.get('items').get('length')
return total_items == 0 ? 0 : (100 * category_items / total_items).toFixed()
}.property('@each.items.length')
})
App.Item = DS.Model.extend({
name: DS.attr('string'),
})
category = App.Category.createRecord({name: 'Category1'})
item = App.Item.createRecord({name: 'Item1'})
category.get('items').pushObject(item)