我应该在我的 Meteor 发布代码中使用全局 "currentUserId" 变量吗?
Should I use a global "currentUserId" var in my Meteor publish code?
在我的 \server\publications.js 文件中,我有这样的代码:
Meteor.publish("jobLocations", function () {
var currentUserId = this.userId;
return JobLocations.find({createdBy: currentUserId});
});
Meteor.publish("workers", function () {
var currentUserId = this.userId;
return Workers.find({createdBy: currentUserId});
});
. . .
IOW,我在每个发布方法中使用了一个名为 "currentUserId" 的本地变量。
改成这样更好吗:
var currentUserId = null;
Meteor.publish("jobLocations", function () {
currentUserId = this.userId;
return JobLocations.find({createdBy: currentUserId});
});
Meteor.publish("workers", function () {
currentUserId = this.userId;
return Workers.find({createdBy: currentUserId});
});
...或者为什么每个发布方法都需要自己的本地 "currentUserId" 变量?
由于 JavaScript 函数 运行 完成,只要没有回调并且它是原始值(不是对象,因为你可能有问题),使用全局不会有问题通过共享和异步函数更改此对象)。
在你的情况下,正如 challett 指出的那样,它是无关紧要的:你立即使用 var
,所以不需要首先声明它。
在我的 \server\publications.js 文件中,我有这样的代码:
Meteor.publish("jobLocations", function () {
var currentUserId = this.userId;
return JobLocations.find({createdBy: currentUserId});
});
Meteor.publish("workers", function () {
var currentUserId = this.userId;
return Workers.find({createdBy: currentUserId});
});
. . .
IOW,我在每个发布方法中使用了一个名为 "currentUserId" 的本地变量。
改成这样更好吗:
var currentUserId = null;
Meteor.publish("jobLocations", function () {
currentUserId = this.userId;
return JobLocations.find({createdBy: currentUserId});
});
Meteor.publish("workers", function () {
currentUserId = this.userId;
return Workers.find({createdBy: currentUserId});
});
...或者为什么每个发布方法都需要自己的本地 "currentUserId" 变量?
由于 JavaScript 函数 运行 完成,只要没有回调并且它是原始值(不是对象,因为你可能有问题),使用全局不会有问题通过共享和异步函数更改此对象)。
在你的情况下,正如 challett 指出的那样,它是无关紧要的:你立即使用 var
,所以不需要首先声明它。