[英]Meteor: Access variable across all Meteor.method's
I'm pretty new to Meteor, but I just made a simple turn-based multiplayer game. 我对Meteor还是很陌生,但是我只是做了一个简单的回合制多人游戏。
When player 2 connects I make an update on the Game collection within a Meteor.method
. 当玩家2连接时,我在Meteor.method
对Game集合进行更新。 But when I, in another Meteor.method
wants to get that update, then I need to Games.find()
it again, to get that updated value. 但是,当我在另一个Meteor.method
想要获取该更新时,则需要再次对Games.find()
进行更新,以获取该更新值。
How can I store the current Game instance, where I can access it with all my Meteor.method's
? 如何存储当前的Game实例,并在其中使用所有Meteor.method's
进行访问?
If it was on client-side, I would use reactive-vars
but I guess that's not an option? 如果是在客户端,我会使用reactive-vars
但是我猜这不是一个选择吗?
Edit: 编辑:
Meteor.methods({
startGame: function() {
return Games.insert({
players: [{
_id: Meteor.userId()
}]
});
},
joinGame: function(game) {
return Games.update({
_id: game._id
}, {
$set: {
endsAt: new Date().getTime() + 10000
},
$push: {
players: Meteor.userId()
}
});
},
getDataFromGame: function() {
// How can I get data from the
// game inside other Methods
// without using Games.find
// ??
}
});
I tried saving the current game inside the methods object, but then it wasn't reactive. 我尝试将当前游戏保存在methods对象中,但随后没有反应。 Don't know what to do next. 不知道下一步该怎么做。
Instead of returning a game from a Meteor.call()
just publish the game(s) the user has joined. 无需从Meteor.call()
返回游戏,只需发布用户已加入的游戏即可。
Meteor.publish('myGames',function(){
return Games.find({ players: { $elemMatch: { _id: this.userId }}});
});
Then on the client: 然后在客户端上:
Meteor.subscribe('myGames');
I should point out that in your code in startGame
the players
key contains an array of objects {_id: Meteor.userId()}
whereas in startGame
the same key just contains an array of user _id
s. 我应该指出,在您的startGame
代码中, players
键包含对象{_id: Meteor.userId()}
的数组,而在startGame
,同一键仅包含用户_id
的数组。 Pick one and go with it. 选择一个并继续使用。 The array form is simpler here in which case your publish function will be: 数组形式在这里更简单,在这种情况下,您的发布功能将是:
Meteor.publish('myGames',function(){
return Games.find({ players: this.userId });
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.