【发布时间】:2014-12-17 08:26:14
【问题描述】:
所以我喜欢使用匿名函数进行编码,而 Meteor.methods 为我打破了这一点。所以我创建了一个这样的 Meteor.Methods
//服务器端
Meteor.startup(function () {
// code to run on server at startup
//expose server methods.
Meteor.methods({
_SERVER_ : function(args){
try{
var funcStr = args.func.split("."); //split on the function parameter
var scopeStr = funcStr[0]; //get the scope of the function
funcStr.splice(0,1); //remove the scope and get the deep path
var path = funcStr.join("."); //join the array and stick it with "."
console.log("util.funcString("+ scopeStr +","+ path +")(" + args.data + ");");
if( myapp.hasOwnProperty(scopeStr) ) //see if the function exist on myapp object
{
var scope = myapp[scopeStr]; //get the scope of the function
var response = util.funcString(scope, path)(args.data); //execute the function
console.log("myapp :" + args.func);
return response;
}else{
return "myapp don't have the method: " + args.func;
}
}catch(e){
return "myapp has a wtf moment and its saying:" + e;
}
}
});
});
因此,该函数几乎希望来自客户端的这样的调用。它会打电话给myapp.page.add
//客户端
Meteor.call("_SERVER_",{
func : "pages.add",
data : page
},function(err, value){
insertNewPage(err,value);
});
好处是我现在可以像这样在服务器端创建一个函数。
//服务器端
myapp.page = (function(){
var privateVar = "private";
//private
function doSomething(){
}
//public via the return object
function add(){
console.log("called from client side");
}
return{
add : add
}
})();
我的应用现在更像是模块化的,可以非常简单地拆分为不同的文件并创建任何你想要的命名空间。
我是否违反了 METEOR 规则?这不安全吗?这是个坏主意?欢迎任何建议,我还是 Meteor 的新手。
谢谢
【问题讨论】:
-
您知道您可以多次拨打
Meteor.methods吗?因此,您可以使用Meteor.methods({"pages.add": function () {.... something ....}});复制上述内容 -
不,我没有,这就是我问的原因。
-
但是您仍然应该在 Meteor.Methods 中为每个函数声明方法。它不仅仅是一个要求在客户端将它们全部统治的呼吁。
-
一次调用而不是直接命名方法有什么好处?
-
我认为任何架构都可以工作,包括您的架构,但以前使用过 Meteor 的人可能希望看到客户端调用的每个函数的显式方法。这有点像为您的 REST API 声明路由 - 它可以让您轻松查看客户端可以访问和不可以访问的内容。
标签: javascript architecture meteor