我有一个名为 Rooms 的集合,现在,我想根据用户在应用程序上的位置发布 Room 的不同子集,所以,这就是我的想法:
Meteor.publish('roomList', function() {
return Rooms.find({}, {fields: {'roomId': 1, 'playerCount': 1, 'isPlaying': 1}});
});
Meteor.publish('roomInfo', function(_id) {
return Rooms.find({_id: _id}, {fields: {'players': 1}});
})
Meteor.publish('roomGame', function(_id) {
return Rooms.find({_id: _id}, {fields: {'game': 1}});
})
当用户只是浏览房间时,我不想限制发送玩家信息的连接,但是,当用户进入房间时,我想为他订阅 roomInfo,以便他可以看到谁在房间里,以及何时在房间里房间正在玩,订阅 roomGame 其中包含游戏信息。 这就是我订阅的方式(此时,用户已经订阅了 roomList)。
Router.route('/sala/:_id', {
name: 'roomLobby',
waitOn: function() {
return this.subscribe('roomInfo', this.params._id);
},
data:function(){
var r = Rooms.findOne(this.params._id);
console.log(r.players);
return r;
}
});
但是,r.players 总是显示为未定义。
我错过了什么?
最佳答案
你的路线逻辑看起来不错。我只会改变几件事:
Router.route('/sala/:_id', {
name: 'roomLobby',
waitOn: function() {
return Meteor.subscribe('roomInfo', this.params._id);
},
data: function() {
if(this.ready()) {
var r = Rooms.findOne(this.params._id);
console.log(r.players);
return r;
}
}
});
我更改的第一件事是在 waitOn
路由选项中使用 Meteor.subscribe()
而不是 this.subscribe()
定义。这是根据文档 here 在 waitOn
路由选项定义中定义订阅句柄的规定方法。 .
我更改的第二件事是将所有代码包装在 if(this.ready()){}
语句中的 data
路由选项定义中。根据文档 here , this.ready()
调用直接绑定(bind)到路线的等待列表并对其使用react,该列表在您定义一个或多个 Meteor.subscribe()
时填充在 waitOn
路由选项定义中调用。
关于javascript - 如何发布具有不同数据子集的同一集合?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30314316/