我是Meteor的新手,所以我可能会错过这里的重要见解。
无论如何,我想向用户表明同时有多少其他用户在网站上。我已经有一个AuditItems
集合,用于存储我可以用于此类计算的who
,when
和what
的kv对。我的Collections
查询使用new Date()
参数运行,所以我不能只观察结果,我必须定期重新运行查询。
然后我通过在changed
上调用Deps.Dependency
来使反应无效。
以下是代码:
// publishing counts of the users that are logged on
// at the moment
Meteor.publish("user-activity", function () {
var self = this;
self.added("user-activity", "all-recent-activity", {'operations': getRecentActivityCountsCache});
self.ready();
Deps.autorun(function() {
self.changed("user-activity", "all-recent-activity", {'operations': getRecentActivityCounts()});
});
});
var getRecentActiveCountsDependency = new Deps.Dependency;
var getRecentActivityCountsCache = 0;
var getRecentActivityCounts = function() {
// register dependency with the caller
getRecentActiveCountsDependency.depend();
var now = new Date();
var aWhileAgo = new Date(now.valueOf() - (5 * 60 * 1000)); // 5 minutes
auditItems = AuditItems.find({'when': { '$gt': aWhileAgo }}).fetch();
console.log('raw data: ' + JSON.stringify(auditItems));
getRecentActivityCountsCache = _.chain(auditItems)
.groupBy('who')
.keys()
.size()
.value();
console.log('new count: ' + getRecentActivityCountsCache);
return getRecentActivityCountsCache;
};
Meteor.setTimeout(function() {
getRecentActiveCountsDependency.changed();
}, 60 * 1000); // 60 seconds
我在计时器第一次触发时在控制台上收到此错误:
Exception from Deps recompute: Error: Can't wait without a fiber
at Function.wait (/home/vagrant/.meteor/tools/3cba50c44a/lib/node_modules/fibers/future.js:83:9)
at Object.Future.wait (/home/vagrant/.meteor/tools/3cba50c44a/lib/node_modules/fibers/future.js:325:10)
at _.extend._nextObject (packages/mongo-livedata/mongo_driver.js:540)
at _.extend.forEach (packages/mongo-livedata/mongo_driver.js:570)
at _.extend.map (packages/mongo-livedata/mongo_driver.js:582)
at _.extend.fetch (packages/mongo-livedata/mongo_driver.js:606)
at _.each.Cursor.(anonymous function) [as fetch] (packages/mongo-livedata/mongo_driver.js:444)
at getRecentActivityCounts (app/server/server.js:26:70)
at null._func (app/server/server.js:12:79)
at _.extend._compute (packages/deps/deps.js:129)
答案 0 :(得分:2)
所有Deps
方法只能在Client上使用。你得到的错误就是建立Deps的方式(因为客户端不使用光纤)。
如果您想在服务器上具有反应性,则需要使用observe
或observeChanges
。使用添加和删除的手柄&您可以在该点查询日期(文档更改时)。
您还可以使用Meteor.setInterval
定期从中删除旧用户。
您可以做的一件事就是使用像meteor-prescence这样的软件包,它可以为您完成所有工作。它的作用是保存一个包含所有在线人员信息的实时集合,然后当他们离线时/超时后,使用定期Meteor.setInterval
方法将其从集合中删除。