Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MeteorJS - Watch for server variable change and update the template value

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!

like image 469
JuanO Avatar asked Feb 11 '23 03:02

JuanO


2 Answers

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.

like image 110
stubailo Avatar answered Apr 08 '23 13:04

stubailo


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

like image 23
coreyb Avatar answered Apr 08 '23 14:04

coreyb