Reputation: 73
I'm trying to make a live updates feed on a Node.js website that would pull the updates from a Firebase realtime database. I manage to make the updates be loaded when the page opens but I'm struggling with making them update in realtime. To be specific: I can't figure out how to pass the database reference object through Handlebars.
So now I pull the updates from the database with:
const getUpdates = () => {
return new Promise((resolve, reject) => {
try {
const ref = firebaseApp.database().ref('liveUpdates');
resolve(ref.once("value"), ref);
} catch (e) {
reject(e);
}
});
};
And then render the page:
exports.loadDashboard = (req, res) => {
getUpdates().then((updates, ref) => {
const updatesList = updates.val();
res.render('index', { updatesList, ref });
return;
});
};
Then I'd like to do something like this in the .hbs file:
<script>
var updates = {{{json ref}}};
updates.on("value" () => {
//Handle update
});
</script>
The json Handlebars helper:
json: (content) => {
return JSON.stringify(content);
}
With this approach the line var updates = {{{json ref}}}; throws an error:
Uncaught SyntaxError: Unexpected token ;
So what am I doing wrong? I haven't worked with Handlebars much before so excuse my ignorance.
Upvotes: 0
Views: 680
Reputation: 199
{{{json ref}}} is a Handlebar/Mustache template, not a valid javaScript code. You put that snippet directly inside "a script tag", marking it as JS code.
If you want to evaluate value of Handlebar expression and assign it to a variable using javaScript you may try using compile method. Something like:
var updates = Handlebars.compile('{{{json ref}}}');
After mastering basic Handlebar examples you might also want to take a look at how to pre-compile templates. This is highly recommended for high-load production environments.
Upvotes: 1