2014-07-03 88 views
0

我的datamodel是一個樣本,它有許多分析。 (想象一下可以多次分析的樣本。)在一對多關係中記錄其中一個記錄的計算屬性

我想在示例模型上創建一個計算屬性,該示例模型根據某些條件獲取其中一個分析,然後可能會在我的模板中顯示該分析。讓我困惑的部分是,許多部分不僅僅是一個屬性,而是一個承諾,所以我不確定如何在我的計算屬性中使用它,以及如何在我的模板中顯示它。

我datamodels低於:

// Define datamodels 
var attr = DS.attr; 

App.Sample = DS.Model.extend({ 
    note: attr('string'), 
    region: attr('string'), 
    timeCollected: attr('string'), 
    sampleID: attr('string'), 
    category: attr('string'), 
    approach: attr('string'), 
    team: attr('string'), 
    location: attr('string'), 
    medium: attr('string'), 
    instrument: attr('string'), 
    asset: attr('string'), 
    mission: attr('string'), 
    analyses: DS.hasMany('analysis', {async: true}), 

    mostImportantAnalysis: function(){ 
    var analysesPromise = this.get('analyses'); 

    // NOW WHAT ??? 

    return importantAnalysis.get('result'); 
    }.property('analyses') 
}); 

App.Analysis = DS.Model.extend({ 
    result: attr('string'), 
    timeAnalyzed: attr('string'), 
    method: attr('string'), 
    agent: attr('string'), 
    sample: DS.belongsTo('sample', { async: true }) 
}); 

回答

0

顯然,你需要等待的承諾先解決......下面是什麼最終爲我工作:

mostImportantAnalysis: function(){ 
    var result = ""; 

    // Make sure the promise resolves before returning 
    var analyses = this.get('analyses'); 
    if(!analyses.get("isFulfilled")) { 
    return ""; 
    } 

    result = analyses.objectAt(0).get('result'); 

    return result; 
}.property('[email protected]') 
0

可以與承諾的工作,如果它是正確加載的對象 -

mostImportantAnalysis: function(){ 
    var analyses = this.get('analyses'); 

    //For example, to get the analysis with the lowest/highest time: 
    mostImportantAnalysis = analyses.sortBy('timeAnalyzed')[0] 

    return mostImportantAnalysis.get('result'); 
}.property('[email protected]') 

請注意,我所做的屬性依賴於分析@每.timeAnalyzed - 這告訴燼,無論何時何種分析在任何分析中發生變化,它都會重新計算以再次找到最重要的分析。

這意味着,雖然分析仍然是一個承諾,但最重要的分析將爲空,但一旦承諾解決,所有時間分析將會改變,最重要的分析將被計算。

爲了您的實際應用中,你可以添加你用它來確定最重要的分析是什麼樣的財產()函數調用例如,任何領域:

財產(「分析@ each.timeAnalyzed」,' 。分析@ each.agent」,‘辦法’,‘儀’)

對於具有更簡單的計算例子,你可以使用灰燼計算性能的宏: http://eviltrout.com/2013/07/07/computed-property-macros.html http://emberjs.com/api/(見API對於各種計算宏)

注意:我不是1 00%確定這個函數是否會在承諾解決之前運行,但是如果有的話,您可能必須執行一個空檢查來避免錯誤。

相關問題