在Ember中加载和使用枚举值

时间:2014-09-19 15:33:47

标签: json ember.js enums

我有一个Ember应用消耗基于rails的webservice。

在Rails方面,我有一些枚举,它们只是数组。 现在,我想在Ember应用程序中检索这些枚举,并将它们渲染为选择值。

webservice返回JSON响应:

get '/grades.json'

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

在Ember方面,我创建了一个像这样的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('grades')。get('model')返回一个空数组[]

关于如何加载和访问此数据的任何想法?

2 个答案:

答案 0 :(得分:1)

所以我最终得到了StudentRoute的直接父母ApplicationRoute,因此在这种情况下需求是相关的。

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')
});

我仍然没有足够的信心确定这是可行的方法,欢迎提出任何建议!

答案 1 :(得分:0)

你只是把你的一些路径搞混了。在StudentsController中,controllers.grades指的是实际的控制器,而不是它的模型。以下代码应该清楚,因为它在命名方面更加明确。

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

另请注意,仅当needs路由是您的grades路由的直接父级时,才能使用students。如果它不是直接的父母,那么您将无法获得所需的数据。