I have a doubt. Not sure if it's possible and didn't find a clear answer about it.
Is it possible to add a "watcher" to a server variable so when the value changes, I can update the view (client side) ?
Let say I have a var counter = 0
and a Timeout function which updates the counter variable every minute.
I want to update a <span>{{counter}}</span>
in the client side. I would need to add a "watcher" to this server variable and make it reactive.
Thanks in advance!
The correct way to do this is to make a collection and store that variable in the collection (even if this means you have a collection with one document).
On server/client common code:
Counter = new Mongo.Collection("counter");
On client make a helper:
Template.myTemplate.helpers({
counter: function () {
return Counter.findOne();
}
});
On server make sure there is a counter:
if (Counter.find().count() === 0) {
Counter.insert({value: 0});
}
Then, on the server increment the counter:
Counter.update({}, {$inc: {value: 1}});
You can use a similar approach if you want to keep track of multiple counters - just insert multiple counters into the collection and reference them by the _id
field.
If your var counter = 0
is server-side code, it will not go out to the clients.
Any server side data that you want to push to clients should be in a Meteor Collection. Then you use the typical publish and subscribe to send updates to the clients.
If you make counter
a session variable, i.e. Session.set('counter', counter++)
, then it will only exist on the client side. Different clients will not have a synchronized value of counter