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

点点圈 提交于 2019-12-06 05:28:38

问题


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!


回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/28056429/meteorjs-watch-for-server-variable-change-and-update-the-template-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!