0

我可能会使用 ArrayController + itemController 设置来解决这个问题,但也许这在模型层内部会更好。

如果属性为空,我想覆盖对象的属性以返回另一个值。我认为这是我在代码中最好的描述(jsfiddle:http: //jsfiddle.net/ahx_/Tqw4C/2/)。

App = Ember.Application.create()

App.Teacher = Ember.Object.extend()

App.Pupil = Ember.Object.extend({
  // TODO Add a property ('answer') that returns teacher.answer unless this.answer is defined
  // Pseudo-code:
  // answer: function(key, value) {
  //  if(Ember.isEmpty(this.answer)) {
  //   return this.get('teacher.answer')
  //  } else {
  //   return this.answer
  //  }
  // }.property('answer')
})

App.IndexController = Ember.Controller.extend({
  init: function() {
    this._super()
    teacher = App.Teacher.create({answer: 'correct'})
    this.set('pupil1', App.Pupil.create({ teacher: teacher, answer: 'incorrect' }))
    this.set('pupil2', App.Pupil.create({ teacher: teacher }))
  }
})
4

1 回答 1

1

您需要添加另一个.property()无法引用自身的属性。

目的:

App.Pupil = Ember.Object.extend({
  answerToShow: function(){
    return this.get('answer') ? this.get('answer') : this.get('teacher.answer')
  }.property('answer')
})

模板:

<script type="text/x-handlebars" data-template-name="index">
  Pupil1 ('incorrect'): {{pupil1.answerToShow}}
  <br>
  Pupil2 ('correct'): {{pupil2.answerToShow}}
</script>

演示:http: //jsfiddle.net/Tqw4C/5/

于 2013-05-04T09:20:43.913 回答