计算属性取决于@each的所有属性

时间:2013-03-28 21:43:43

标签: ember.js

我之前使用的计算属性类型如下:

isAnyoneHungry: function () {
  var everyone = this.get('everyone'),
      anyoneHungry = false;
  everyone.forEach(function(person) {
    if (person.get('isHungry')) {
      anyoneHungry = true;
    }
  });
  return anyoneHungry;
}.property('everyone.@each.isHungry'),

everyone: Ember.A() // an array that will hold person models

用于根据数组中每个对象的一个​​属性计算内容。

是否可以根据数组中每个对象的每个属性创建一个计算属性? 假设person模型有许多布尔属性,如isHungryisTiredisCranky,...我希望能够在任何一个属性中重新计算此属性变化。但我很懒,不想像这样输入每一个属性:

function(){...}.property('everyone.@each.isHungry', 'everyone.@each.isTired', 'everyone.@each.isCranky'.

相反,我想要这样的事情:

isAnyoneUnhappy: function () {
  var everyone = this.get('everyone'),
      isAnyoneUnhappy = false;
  everyone.forEach(function (person) {
    if (person.get('isHungry') || person.get('isTired') || person.get('isCranky')) {
      isAnyoneUnhappy = true;
    }
  });
  return isAnyoneUnhappy;
}.property('everyone.@each.iWantEveryPropertyHere')

这可能在Ember吗?

2 个答案:

答案 0 :(得分:0)

您是否尝试过以下操作?

isAnyoneUnhappy: function () {
  var everyone = this.get('everyone'),
      isAnyoneUnhappy = false;
  everyone.forEach(function (person) {
    if (person.get('isHungry') || person.get('isTired') || person.get('isCranky')) {
      isAnyoneUnhappy = true;
    }
  });
  return isAnyoneUnhappy;
}.property('everyone.@each.*')

我查看了Ember源代码,似乎有一些处理星形符号的逻辑。我不确定。

答案 1 :(得分:0)

理想情况下,你应该在人身上有一个卷起不愉快属性的属性,例如:

isUnhappy: function () {
  if (this.get('isHungry') || this.get('isTired') || this.get('isCranky')) {
    return true;
  }
}.property('isTired', 'isHungry', 'isCranky')

然后isAnyoneUnhappy只观察everyone.@each.isUnhappy