I want to try Meteor so I stated developing a small multi-rooms chat app in coffeescript. I am having problem passing the result of a findOne to html page using handlebars.
if Meteor.is_client
room=Rooms.findOne({id:1})
Template.room({room_name:room.name})
in the html page
<head>
<title>Chat!</title>
</head>
<body>
{{> room}}
</body>
<template name="room">
Welcome to {{room_name}}
</template>
Now, given that the room document with id = 1 has name = 'Room1', I'd expect the page to render 'Welcome to Room1' but got a whitepage and the console shows 2 errors:
Uncaught TypeError: Cannot read property 'name' of undefined
Uncaught TypeError: Cannot read property 'room_name' of undefined
apparently room is undefined even if that document actually exists.
It's undefined for a split second, before the client database cache has time to sync to the server. The template is supposed to render again once the client syncs, but since it threw an error the first time that won't happen (I was confused by a similar problem recently).
Try this (using short-circuit &&
to test that room exists):
if Meteor.is_client
Template.room.room_name = ->
room = Rooms.findOne({id:1})
room && room.name
Note: I moved the findOne
call into the function to make sure it gets called when updates happen, but it may have also been fine where you had it
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With