2014-09-19 19 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