好的,这是一个完全有效的解决方案,它跟踪当前查看特定路线路径的用户并通过帮助程序显示此用户列表。这在您使用的假设下有效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 {{> yield}} 的内容,直到 waitOn(全局和特定于路由的)订阅准备好。
我也遇到了浏览器控制台错误,据我所知,这似乎并没有阻碍任何事情,但我不喜欢它在那里:'Error invoking Method 'eventsOnHooksInit': Method not found [404]'