如果您愿意使用 Meteor 的 Auth 分支,这就是我添加一些注释所做的。我不喜欢乔希的回答,因为我不信任客户!他们说谎。
在这个例子中,我们会说每个用户都有一个魔法对象。我们拒绝使用用户可以操纵客户端的任何信息(即会话变量)。
在服务器上:
//Create our database
MagicalObjects = new Meteor.Collection("magicalObjects");
// Publish the magical object for the client
Meteor.publish("get-the-magical-object", function () {
//In the auth branch, server and client have access to this.userId
//And there is also a collection of users server side
var uid = this.userId();
//I make sure that when I make this connection, I've created a magical object
//for each user.
//Let's assume this adds a parameter to magical object for the userId
//it's linked to (i.e. magObject.uid = ~user id~ )
//we grab our current user from the users database, and pass to our function
checkUserHasMagicalItem(Meteor.users.findOne({_id: uid}));
var self = this;
console.log('Writing publish');
console.log('uid: ' + this.userId());
var magicalObject = MagicalObjects.findOne({uid: uid});
//Now, I want to know if the magical object is changed -- and update accordingly
//with its changes -- you might not need this part
//If you don't- then just uncomment these two lines, ignore the rest
//self.set("magicObject", uid, {magicalobject: magicalObject});
//self.flush();
//Here, we're going to watch anything that happens to our magical object
//that's tied to our user
var handle = MagicalObjects.find({uid: uid}).observe({
added: function(doc, idx)
{
//get the latest version of our object
magicalObject = MagicalObjects.findOne({uid: uid});
console.log('added object');
//now we set this server side
self.set("magicObject", uid, {magicalobject: magicalObject});
self.flush();
},
//I'm not concerned about removing, but
//we do care if it is changed
changed: function(newDoc, idx, oldDoc)
{
console.log('changed object');
magicalObject = MagicalObjects.findOne({uid: uid});
self.set("magicObject", uid, {magicalobject: magicalObject});
self.flush();
}
//end observe
});
//for when the player disconnects
self.onStop(function() {
console.log('Stopping');
handle.stop();
//end onStop
});
//end publish
});
在客户端:
//this is the name of our collection client side
MagicalObject = new Meteor.Collection("magicObject");
//notice the name is equal to whatever string you use when you call
//self.set on the server
//notice, this is the name equal to whatever string you use when you
//call Meteor.publish on the server
Meteor.subscribe("get-the-magical-object");
然后,当你想去拿你的魔法物品时:
var magicObject = MagicalObject.findOne().magicalobject;
请注意,.magicalobject 不是拼写错误,它是我们在 self.set 中使用的参数——{magicalobject: magicObject}。
我为冗长的回答道歉。但要快速总结一下:我们做了什么?
在服务器上,我们有一个客户端无法访问的 MagicalObjects 集合。相反,我们从魔法对象中发布一个对象——我们称之为“magicalObject”。根据我们的设置,每个对象都属于一个用户。因此,它是操作请求的用户特定对象。
客户端创建一个集合(其名称为“magicalObject”),然后在服务器数据库中的实际数据发生变化时发送数据。这个集合在设计上只有一个对象,但该对象可以有许多参数(例如magicObject.kazoo 或magicObject.isHarryPotter),或者您可以存储许多不同的对象(例如nonMagicItem)。