我创建了测试 Meteor 应用程序,我发现整个代码(也包括服务器端)可用于在客户端上使用开发工具查看。 测试应用(在浏览器中):
(function(){ if (Meteor.isClient) {
Template.hello.greeting = function () {
return "Welcome to test_app.";
};
Template.helo.events({
'click input' : function () {
// template data, if any, is available in 'this'
if (typeof console !== 'undefined')
console.log("You pressed the button");
}
});
}
if (Meteor.isServer) {
Meteor.startup(function () {
// code to run on server at startup
});
}
}).call(this);
这是设计使然吗?服务器端代码可以留在服务器吗?
最佳答案
如果您想在服务器上保留服务器端代码,您必须重构您的应用。
将这些目录放在应用程序的根目录中:
- /server - 存储仅在服务器上运行的所有内容
- /client - 存储仅在客户端上运行的所有内容
- /public/- 存储任何可以在
http://yoursite/
中访问的内容(即图像、字体)。如果您将图像a.jpg
放在/public
中,它将在http://yoursite/a.jpg
中可用
一旦你使用这个结构,你就不必使用 if(Meteor.isServer) {..}
或 if(Meteor.isClient) {..}
不再有条件,因为它们会在正确的地方运行。
当你把文件放在你的 meteor 应用程序的根目录中时,它们将同时在客户端和服务器上运行,所以这就是为什么文件没有改变以及 if( Meteor.isServer)
只会在服务器上运行。
这是设计使然,并且在服务器和客户端之间共享代码非常有帮助,尽管它对客户端和服务器都是可见的
关于javascript - Meteor 后端代码是否始终在客户端可用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18142805/