gpt4 book ai didi

javascript - Meteor - 为什么我应该尽可能使用 this.userId 而不是 Meteor.userId() ?

转载 作者:可可西里 更新时间:2023-11-01 09:07:19 33 4
gpt4 key购买 nike

this comment来看作者:David Glasser 在 GitHub 问题中:

this.userId is the primary API and Meteor.userId() is syntactic sugar for users new to JavaScript who might not understand the details of successfully using this yet

似乎我们应该尽可能使用this.userId(比如在方法函数中,你可以同时使用两者),并且只使用Meteor.userId() 内部发布功能。如果这个假设是正确的,为什么

(引用代码的相关部分也有帮助,我似乎找不到)

最佳答案

您的问题似乎混淆了 Meteor.userId()Meteor.user()。问题的主体似乎是在问前者,而主题行是在问后者。我会尝试解决这两个问题。

  1. 在服务器上,在发布函数中,调用 Meteor.userId()Meteor.user()cause an error .相反,请分别使用 this.userIdMeteor.users.findOne(this.userId)。但是,请注意发布函数仅在客户端订阅时调用。如果您希望发布在用户记录更改时更改,则需要 observe() Meteor.users.find(this.userId) 返回的游标和当记录发生变化时采取适当的行动。
  2. 在服务器上,当一个方法调用被处理时,Meteor.userId()Meteor.user() 将对应于调用用户和他们的记录,分别。但是,请注意调用 Meteor.user() 将导致数据库查询,因为它们是 essentially equivalent to Meteor.users.findOne(Meteor.userId())。 .

    直接在方法调用中,您也可以使用 this.userId 代替 Meteor.userId(),但您不太可能看到显着的性能差异。当服务器接收到方法调用时,它 runs your method implementation with the user's ID (and some other info)存储在特定的 slot在纤维上。 Meteor.userId() 只是从当前光纤的插槽中检索 ID。那应该很快。

    重构使用 Meteor.userId() 的代码通常比使用 this.userId 更容易,因为您不能使用 this.userId在方法体之外(例如 this 在您从方法体调用的函数中不会有 'userId' 属性)并且您不能使用 this.userId在客户端上。

  3. 在客户端,Meteor.userId()Meteor.user() 不会抛出错误,this.userId 将不起作用.对 Meteor.user() 的调用是 essentially equivalent to Meteor.users.findOne(Meteor.userId()) ,但由于这对应于一个迷你 mongo DB 查询,性能可能不会成为问题。但是,出于安全原因,Meteor.user() 返回的对象可能不完整(特别是如果未安装 autopublish 包)。

关于javascript - Meteor - 为什么我应该尽可能使用 this.userId 而不是 Meteor.userId() ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32800211/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com