【问题标题】:Trouble accessing model properties in controller无法在控制器中访问模型属性
【发布时间】:2015-05-05 19:16:59
【问题描述】:

我有一个组件可以像这样从我的控制器中获取一些当前的夹具数据

{{vertical-graph metrics=controller.total_sessions_comparison}}

控制器属性如下所示

total_sessions_comparison: [
    [
        {
            metricNumber: "26%",
            metricText: "September",
            metricStyle: "height: 26%"
        },
        {
            metricNumber: "22%",
            metricText: "October",
            metricStyle: "height: 22%"
        },
    ],
    [
        {
            metricNumber: "74%",
            metricText: "September",
            metricStyle: "height: 74%"
        },
        {
            metricNumber: "78%",
            metricText: "October",
            metricStyle: "height: 78%"
        }
    ]
],

我的路由器中的模型挂钩正在从这样的自定义 express api 加载数据

return Ember.$.getJSON('http://127.0.0.1:3000/api');

目前我的 API 正在返回如下所示的 JSON

{
"total_sessions": 288,
"current_month": "May",
"current_month_year": "2015",
"last_month": "December",
"last_month_year": "2014"
}

我可以很好地访问模板中的模型数据(这些都在索引下)但是我在理解如何在控制器属性中获取月份名称而不是硬编码它们时遇到了一些问题通过 API 动态传递。模型属性看起来像 current_monthlast_month,就像我说的在模板中工作,但我无法让它们在控制器中工作。

或者有没有比我目前更好的方法可以让这更容易?

【问题讨论】:

  • 你的问题对我来说没有多大意义。你只是随机开始谈论几个月,但控制器属性是关于指标的,我在任何地方都看不到 current_monthlast_month。告诉我你的路线代码
  • 用我的 JSON API 的当前响应更新了它,路由代码也是 Ember.$.getJSON(...) 位,它在索引路由的模型钩子中。
  • 这是一个开始。现在“让它们在控制器中工作”是什么意思
  • 所以在控制器属性中我有月份作为字符串,但我想使用从 JSON API 传递的那些而不是写出来。这有意义吗?

标签: json ember.js model controller


【解决方案1】:

好的,默认情况下,从路由中的model 挂钩返回的内容被设置为相应控制器上的model 属性。这是通过内置的setupController(controller, model) 钩子完成的。如果您想在控制器上设置更多属性或需要更细粒度的控制,请随意覆盖 setupController。例如,您的 json 被解析为一个对象,该对象在 promise 解决时设置为模型。要将控制器上的 current_month 变量设置为此值,您可以:

setupController: function(controller, model){
    controller.set('current_month', model.current_month);
}

您不再需要设置模型,除非您需要 this._super(controller, model) 在覆盖的 setupController 内。

【讨论】:

  • 所以我添加了last_month 的代码并向控制器添加了一个空属性,但我仍然无法从控制器内部调用该属性。我怎么称呼它?
  • 打电话?如果您尝试访问该属性,请使用this.get('last_month')。这样做只能在函数内部完成。
  • 是的,在控制台中当我尝试这样做时看到此错误Error while processing route: index this.get is not a function TypeError: this.get is not a function
  • this.get() 应该在控制器而不是路由中发生。请显示失败的控制器代码
  • total_sessions_comparison: [ [ { metricNumber: "26%", metricText: this.get('last_month'), metricStyle: "height: 26%" }, { metricNumber: "22%", metricText: "October", metricStyle: "height: 22%" }, ], [ { metricNumber: "74%", metricText: "September", metricStyle: "height: 74%" }, { metricNumber: "78%", metricText: "October", metricStyle: "height: 78%" } ] ],
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-05-04
  • 2014-05-16
  • 2015-08-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多