使用Meteor,我试图了解何时使用服务器端,Meteor.methods()同时仍保留即时UI更新.
从Andrew Scala的介绍性教程中,他声称Meteor.methods()应该在您想要更新和修改数据库文档时使用:
我们的想法是,您定义服务器上执行修改和更新数据等危险内容的所有功能,然后让客户端调用这些函数并获取常规函数等返回值.客户端永远不会看到实现,也不会亲自修改数据.服务器完成所有工作.
遵循这个建议,我在我的代码中实现了这个:
服务器端:
Meteor.methods({
addMovie: function(data) {
var movie = Movies.insert({name: data});
return movie;
},
...
Run Code Online (Sandbox Code Playgroud)
客户端:
Template.movies.events = ({
'click #add-movie': function(e) {
var name = document.getElementById('movie-name').value;
Meteor.call('addMovie', name);
return false;
},
...
Run Code Online (Sandbox Code Playgroud)
这有效,但速度很慢.UI不会像Movies.insert()在客户端调用时那样立即更新.该文件表明,以纠正问题,您可以创建在客户端存根:
客户端上的调用方法定义与同名服务器方法关联的存根函数.如果您不希望,则不必为方法定义存根.在这种情况下,方法调用就像其他系统中的远程过程调用一样,您必须等待服务器的结果.
但这些存根应该是什么样的?它应该与服务器端方法基本相同吗?如果是这样,重点是什么?我正在寻找关于Meteor.methods()存根的使用和目的,点/使用及其实现的更全面的解释.
编辑:大卫格林斯潘已帮助阐明Meteor.methods()和存根在流星谈话中的使用.
我在使用Fibers/Meteor.bindEnvironment()时遇到了困难.如果集合开始为空,我尝试更新代码并插入集合.这应该是在启动时运行服务器端.
function insertRecords() {
console.log("inserting...");
var client = Knox.createClient({
key: apikey,
secret: secret,
bucket: 'profile-testing'
});
console.log("created client");
client.list({ prefix: 'projects' }, function(err, data) {
if (err) {
console.log("Error in insertRecords");
}
for (var i = 0; i < data.Contents.length; i++) {
console.log(data.Contents[i].Key);
if (data.Contents[i].Key.split('/').pop() == "") {
Projects.insert({ name: data.Contents[i].Key, contents: [] });
} else if (data.Contents[i].Key.split('.').pop() == "jpg") {
Projects.update( { name: data.Contents[i].Key.substr(0,
data.Contents[i].Key.lastIndexOf('.')) },
{ $push: {contents: data.Contents[i].Key}} );
} else {
console.log(data.Contents[i].Key.split('.').pop());
}
}
});
} …Run Code Online (Sandbox Code Playgroud)