2013-05-03 68 views
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 })) 
    } 
}) 
+1

你最好的選擇可能是隻定義了不同名稱的計算性能。我認爲在空值的情況下定義回退默認靜態文本的Handlebars助手雖然不錯,儘管如此,這並不適用於你的情況。 – mehulkar 2013-05-03 17:02:11

回答

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/

相關問題