Here’s the great thing about Meteor: you don’t have to reload the page in order to see changes in data. It’s referred to as reactivity. Certain data in Meteor is referred to as being reactive, such as a mongo cursor, or reactive variable.
Building off of the previous example, let’s make a publication on the server for our client to subscribe to:
Meteor.publish('busStateAtTime', function (busName, time) {
return BusTimetables.find({
bus: busName,
startTime: {
$lte: time
},
endTime: {
$gt: time
}
});
});
On the client we’ll need to do two things, make a reactive variable to represent a time and subscribe to the publication so that we can get new information as the time changes.
Using reactive var, lets make the variable and update it every minute.
const whatTimeIsIt = new ReactiveVar();
// set interval lets you run a function every _____ milliseconds
Meteor.setInterval(() => {
const h = (new Date()).getHours(); // hours
const m = (new Date()).getMinutes(); // minutes
const timeAsAString = `${h}${m}`; // convert to a string
const timeAsANumber = parseInt(timeAsAString); // convert to a number
whatTimeIsIt.set(timeAsANumber); // update our reactive variable
}, 60 * 1000); // 60 * 1000 = 60,000ms (1 minute)
Now that we have a reactive variable that is updated every minute, we want to use that to subscribe to the publication we created earlier. We will use Tracker so that our subscription updates each time our reactive variable updates.
Tracker.autorun(() => {
Meteor.subscribe('busStateAtTime', 'A', whatTimeIsIt.get());
});
Then, when you want to access this document that represents the bus’s state, you can do so with:
BusTimetables.findOne({
bus: 'A',
startTime: {
$lte: whatTimeIsIt.get()
},
endTime: {
$gt: whatTimeIsIt.get()
}
});
BusTimetables.findOne is also a reactive data-source, so depending on which frontend framework you choose, you’ll be able to ensure your UI updates as the bus timetable document changes.