MeteorJS - 监视服务器变量更改并更新模板值 [英] 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) ?
假设我有一个 var counter = 0
和一个每分钟更新计数器变量的超时函数.
Let say I have a var counter = 0
and a Timeout function which updates the counter variable every minute.
我想在客户端更新一个{{counter}}
.我需要向这个服务器变量添加一个观察者"并使其反应性.
提前致谢!
推荐答案
正确的做法是创建一个集合并将该变量存储在该集合中(即使这意味着您的集合只有一个文档).
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");
在客户端做一个帮手:
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}});
如果您想跟踪多个计数器,您可以使用类似的方法 - 只需将多个计数器插入到集合中并通过 _id
字段引用它们.
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.
这篇关于MeteorJS - 监视服务器变量更改并更新模板值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!