我正在尝试使用 Javascript 为我的 Meteor 应用制作一个标志,说明当前有多少用户在我的网站上(我不知道这是否会有所不同)。我有这段代码可以跟踪一次网站上有多少用户:
Presences.find({online: true}).count();
但是我如何使用 HTML 在我的网站上显示它呢?我认为 Meteor 的组织方式会使事情变得更加困难。
哦,我还应该提一下,我在这个项目中安装了 iron-router 包,所以模板有点不同。这可能会影响代码?
最佳答案
有点棘手,你需要一个自定义的发布函数和一个客户端的虚拟集合(userCount
)
这只会发布在线用户数,并使用 Observer 查询更改它。
这样您就不必发布在线用户的所有文档 :) 所以当您有更多的用户时它不会减慢您的客户端的速度。
服务器端代码
Meteor.publish("userCount", function() {
var self = this;
var presences = Presences.find({online: true});
var count = presences.count();
var handle = presences.observe({
added: function() {
if(!handle) return;
count++;
self.changed('userCount', 'count', {count: count});
},
removed: function() {
count--;
self.changed('userCount', 'count', {count: count});
}
});
self.added('userCount', 'count', {count: count});
self.onStop(function() {
handle.stop();
});
this.ready();
});
客户端代码
var userCount = new Meteor.Collection("userCount");
Meteor.subscribe("userCount");
HTML(示例)
<template name="example">
{{userCount}}
</template>
模板助手
Template.example.userCount = function() {
var count_doc = userCount.findOne({_id:'count'});
return (count_doc && count_doc.count) || 0;
}
关于javascript - 如何在 HTML 中显示此代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22797826/