我想显示当前在线和的用户专注于特殊页面。在这个页面的某个地方,我想显示用户列表和状态(在线/离线焦点/无焦点)
我找到了这个包:benjaminrh/event-hooks
设置很明确,这是在文档中。但我不明白如何使用钩子。例如:
Hooks.onLoseFocus = function ([server: userId]) { ... }
(任何地方) - 提供在窗口失去焦点时运行的回调。
因此该函数采用userId。
考虑到上面的布局,我会在某处有一个额外的模板和每个循环,如:
{{#each userstatus}}
{{>users_stats}
{{/each}}
当钩子占用单个userIds时,如何创建userstatus?
答案 0 :(得分:1)
好的,这是一个完全有效的解决方案,可以跟踪当前正在查看特定路径路径的用户,并通过帮助程序显示此用户列表。这可以在您使用iron:router
:
服务器强>:
Hooks.onCloseSession = function() {
Meteor.call('clearUserFocus', function(error, result) {
if(error)
console.log(error);
});
}
Meteor.methods({
'setUserFocus': function(_routePath) {
Meteor.users.update({_id: Meteor.userId()}, {$set: {focus: _routePath}});
},
'clearUserFocus': function() {
var userId = Meteor.userId();
Meteor.users.update({_id: userId}, {$unset: {focus: ''}});
}
});
onCloseSession
似乎只能在服务器中可靠地工作,正如您所期望的那样。
<强>客户端强>:
Meteor.startup(function() {
// Start hooks, for user focus tracking
Hooks.init({
updateFocus: 500
});
});
Hooks.onGainFocus = function() {
// Router.current().route.getName(); // route name
var routePath = Iron.Location.get().pathname; // route path
Meteor.call('setUserFocus', routePath, function(error, result) {
if(error)
console.log(error);
});
}
Hooks.onLoseFocus = function() {
Meteor.call('clearUserFocus', function(error, result) {
if(error)
console.log(error);
});
}
客户全局路由器:
Router.onBeforeAction(function() {
// Record user focus
var routePath = Iron.Location.get().pathname;
Meteor.call('setUserFocus', routePath, function(error, result) {
if(error)
console.log(error);
});
this.next();
});
客户模板助手:
Template.yourTemplateName.helpers({
'focusedUsers': function() {
var routePath = Iron.Location.get().pathname;
return Meteor.users.find({focus: routePath});
}
});
客户模板:
<ul>
{{#each focusedUsers}}
<li>{{_id}}</li>
{{/each}}
</ul>
这对我来说非常好,我需要彻底测试它,尽管我已经发现了至少一个警告。有多个窗口运行,似乎它可能会与焦点混淆。
另请注意,您需要所有路由才能访问users
发布(无论您的名称是什么),以便帮助程序可以访问该集合并获取focus
。您可以这样做:
// Global router settings
Router.configure({
layoutTemplate: 'defaultLayout',
loadingTemplate: 'loading',
waitOn: function() {
return Meteor.subscribe('users');
}
});
根据要求:请注意,这包括默认布局和加载模板的可选示例。加载模板替换了layoutTemplate {{&gt; yield}},直到waitOn(特定于全局和路由)订阅准备就绪。
我也遇到了浏览器控制台错误,就我所知,这似乎并不妨碍任何事情,但我不喜欢它在那里:&#39;错误调用方法&#39; eventsOnHooksInit&#39;:未找到方法[404]&#39;