2014-09-19 64 views
1

我有一個使用基於軌道的web服務的Ember應用程序。在Ember中加載和使用枚舉值

在Rails方面,我有一些枚舉,他們只是數組。 現在,我想要在Ember應用中檢索這些枚舉,並將它們呈現爲選擇值。

的web服務返回的JSON響應:

get '/grades.json'

{"grades":["cp","ce1","ce2","cm1","cm2"]}

在灰燼的一面,我創建了一個GradesRoute這樣的:

App.GradesRoute = Ember.Route.extend({ 
    model: function() { 
     return Em.$.getJSON('api/v1/grades.json') 
    } 
})); 

然後,我想我需要它在這些枚舉正在使用的控制器中:

App.StudentsController = Ember.ArrayController.extend({ 
    needs: ['grades'], 
    grades: Ember.computed.alias('controllers.grades') 
} 
)); 

所以至少我認爲我可以遍歷students模板中的成績。

{{#each grade in grades}} 
    {{grade}} 
{{/each}} 

但我從模板,沒有輸出...調試試圖templateContext.get(「成績」)。獲得(「模型」)返回一個空數組[]

任何想法關於如何加載和訪問這些數據?

回答

0

你只是有一些混淆了你的路徑。在StudentsController,controllers.grades是指實際的控制器,而不是它的型號。下面的代碼應該清理一些事情,因爲它在命名上更加明確。

App.StudentsController = Ember.ArrayController.extend({ 
    needs: ['grades'], 
    gradesController: Ember.computed.alias('controllers.grades'), 
    grades: Ember.computed.alias('gradesController.model.grades') 
}); 

此外,要知道,如果你的grades路線是你students路線的直接父,使用needs纔有效。如果它不是直接的父母,那麼您將無法取回所需的數據。

+0

謝謝。雖然,成績應該是其他模式之間的共享資源,但我認爲我走錯了路。爲學生設置成績路線作爲家長是沒有意義的。我將嘗試使用應用程序控制器來控制等級。 – demental 2014-09-19 21:54:32

1

所以我結束了ApplicationRoute,這是StudentRoute的直接父項,所以需要在這種情況下是相關的。

App.ApplicationRoute = Ember.Route.extend({ 
    setupController: function(controller) { 
    Em.$.getJSON('api/v1/enums.json').then(function(data){ 
     controller.set('grades', data['grades']); 
     controller.set('states', data['states']); 
    } 
    } 
}); 

現在我可以爲我需要使用的每個枚舉創建一個別名。

App.StudentsController = Ember.ArrayController.extend({ 
    needs: ['application'], 
    grades: Ember.computed.alias('controllers.application.grades'), 
    states: Ember.computed.alias('controllers.application.states') 
}); 

我還沒有足夠的信心去確定這是要走的路,任何建議都是值得歡迎的!

+0

您在此處切換到咖啡腳本時感到困惑。您可能需要更新問題(或此)以符合語法。 – 2015-03-20 14:15:29

+0

對不起,我的懶惰......我原本使用Emberscript工作在這個項目上,但又回到了javascript,其中一個原因是在這裏這樣的地方分享和討論更容易。所以,編輯完成。 – demental 2015-03-21 17:31:37