【问题标题】:Beginner Meteor: template and findOne初学者流星:模板和findOne
【发布时间】:2012-05-11 03:27:36
【问题描述】:

我想尝试 Meteor,所以我说要在 coffeescript 中开发一个小型多房间聊天应用程序。 我在使用把手将 findOne 的结果传递给 html 页面时遇到问题。

if Meteor.is_client
  room=Rooms.findOne({id:1})
  Template.room({room_name:room.name})

在html页面中

 <head>
  <title>Chat!</title>
 </head>
 <body>
   {{> room}}
 </body>

<template name="room">
 Welcome to {{room_name}}
</template>

现在,鉴于 id = 1 的房间文档的名称 = 'Room1',我希望该页面呈现“欢迎来到 Room1”,但得到一个白页,并且控制台显示 2 个错误:

Uncaught TypeError: Cannot read property 'name' of undefined
Uncaught TypeError: Cannot read property 'room_name' of undefined

即使该文档确实存在,显然房间也是未定义的。

【问题讨论】:

    标签: handlebars.js meteor


    【解决方案1】:

    由于您使用的是 Coffeescript,存在运算符“?”也可以使用:

    Template.room.helpers
        room_name: -> Rooms.findOne(id: 1)?.name
    

    【讨论】:

      【解决方案2】:

      在客户端数据库缓存有时间同步到服务器之前,它是未定义的。一旦客户端同步,模板应该会再次呈现,但由于它第一次抛出错误,因此不会发生(我最近被类似的问题弄糊涂了)。

      试试这个(使用短路&amp;&amp; 来测试房间是否存在):

      if Meteor.is_client
          Template.room.room_name = ->
              room = Rooms.findOne({id:1})
              room && room.name
      

      注意:我将 findOne 调用移到了函数中,以确保在发生更新时调用它,但在你使用它的地方也可能没问题

      【讨论】:

      • 非常感谢 danny,解决了问题。
      • 谢谢 - 完美的解决方案。两者都返回了,并且效果很好。两者都赞成。
      猜你喜欢
      • 2016-02-05
      • 2012-11-16
      • 2018-07-02
      • 1970-01-01
      • 1970-01-01
      • 2011-05-23
      • 1970-01-01
      • 1970-01-01
      • 2014-04-25
      相关资源
      最近更新 更多