【问题标题】:Should I use a global "currentUserId" var in my Meteor publish code?我应该在 Meteor 发布代码中使用全局“currentUserId”变量吗?
【发布时间】:2015-10-02 13:30:19
【问题描述】:

在我的 \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”变量是否有某些原因?

【问题讨论】:

  • 你不需要使用var,你可以在需要的地方使用this.userId..
  • 好点;我只是使用“Your First Meteor App”中的示例代码,并没有用批判的眼光看待它。

标签: meteor global-variables publish-subscribe


【解决方案1】:

由于 JavaScript 函数一直运行到完成,所以只要没有回调并且它是原始值(不是对象,因为您可能会遇到传递共享和异步函数的问题),使用全局就不会出现问题改变这个对象)。

在您的情况下,正如 challett 指出的那样,这无关紧要:您立即使用 var,因此无需一开始就声明它。

【讨论】:

    猜你喜欢
    • 2014-04-04
    • 2018-09-21
    • 2012-02-25
    • 1970-01-01
    • 2010-10-21
    • 1970-01-01
    • 2015-02-15
    • 1970-01-01
    • 2011-10-11
    相关资源
    最近更新 更多