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!
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 ofcounter
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:
On client make a helper:
On server make sure there is a counter:
Then, on the server increment the counter:
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.