Emberjs #each循环不能处理数组数据

时间:2016-05-10 05:25:37

标签: javascript ember.js

我只是试图遍历我生成的一些虚拟数据,因此我可以设置网站的样式,我在路由器中有这个:

import Ember from 'ember';

export default Ember.Route.extend({
  chatMessages() {
      return [{
      username: "John Doe",
      message: "Blah Blah Blah",
      dispic: "http://www.proirrigationwi.com/images/unknown_user.png"
    }]
  },
  activate() {
    this.controllerFor('chatroom').subscribe();
  }
});

然后在我的index.hbs

    {{#each chatMessages as |chatMessage|}}
      {{chat-message username=chatMessage.username message=chatMessage.message dispic=chatMessage.dispic}}
    {{else}}
      {{chat-message username="System" message="There are currently no chat messages, feel free to start talking! Someone will join eventually" dispic="asd"}}
    {{/each}}

但我只看到了其他声明。任何信息都会很棒,谢谢

1 个答案:

答案 0 :(得分:1)

您的路线目前设置不正确,您必须在路线模型中返回聊天消息:

import Ember from 'ember';

export default Ember.Route.extend({
  chatMessages: [{
      username: "John Doe",
      message: "Blah Blah Blah",
      dispic: "http://www.proirrigationwi.com/images/unknown_user.png"
  }],
  model(){
    return this.get('chatMessages')
  },
  activate() {
    this.controllerFor('chatroom').subscribe();
  }
});

现在,您可以在模板中访问它,如下所示:

{{#each model as |chatMessage|}}
  {{chat-message username=chatMessage.username message=chatMessage.message dispic=chatMessage.dispic}}
{{else}}
  {{chat-message username="System" message="There are currently no chat messages, feel free to start talking! Someone will join eventually" dispic="asd"}}
{{/each}}

以下是我为您设置的twiddle。然后重要的是再次阅读指南的this section,因为它在路线方面更详细地解释了模型钩子,并且this part解释了如何在控制器上设置它。