计算属性和@每个

Computed Properties and @each

本文关键字:每个 属性 计算      更新时间:2023-09-26

我一直在阅读文档和API,很难找到以下内容的解释:

export default Ember.Controller.extend({
  collectionTotal: function() {
    var games = this.get('model');
    return games.length
  }.property('@each')
});

.property('@each')实际发生了什么?我知道我正在取回计算的属性,我不明白@each是什么。

什么是@each

@each观察数组中每个项的单独属性。

例如,如果我观察到users.@each.name,我将收到一个事件,如果:

  • users属性被替换,例如this.set('users', ...)
  • users中添加或删除项目
  • 任何项的name属性都会更改

您可以使用以下语法观察多个属性:users.@each.{name,email}

你不能给它们筑巢。这将不起作用:users.@each.friends.@each.mood

阅读更多官方文档:

  • 计算属性和使用@each聚合数据
  • Ember.ArrayProxy类

回答您的问题

@each本身没有意义。如果只需要注意添加或删除的项目,则可以观察[]属性。

通常,您应该观察函数体中使用的相同属性。在您的示例中,这将是modellength:

  collectionTotal: function() {
    var games = this.get('model');
    return games.get('length');
  }.property('model.length')

或者等效地:

  collectionTotal: function() {
    return this.get('model.length');
  }.property('model.length')

或者等效地:

  collectionTotal: Ember.computed.reads('model.length')