gpt4 book ai didi

meteor - meteor -在客户端启动时使用集合

转载 作者:行者123 更新时间:2023-12-03 11:37:24 24 4
gpt4 key购买 nike

为什么此代码显示为“0”?它不应该返回“1”吗?

Messages = new Meteor.Collection("messages");

if (Meteor.is_client) {
Meteor.startup(function () {
alert(Messages.find().count());
});
}

if (Meteor.is_server) {
Meteor.startup(function () {
Messages.insert({text: "server says hello"});
});
}

如果以后再执行“Messages.find()。count()”,它将返回1。

最佳答案

默认情况下,当Meteor客户端启动时,它将连接到服务器并订阅您定义的任何Meteor.Collection中的文档。这需要一些时间才能完成,因为建立服务器连接和接收文档总是会出现一些延迟。

客户端上的Meteor.startup()与jQuery中的$()非常相似-一旦客户端DOM准备就绪,它就会运行其参数。它不会等待客户端的集合从服务器接收其所有文档。因此,以您编写代码的方式,对find()的调用将始终运行得太早并返回0。

如果要等到代码首次从服务器下载后才运行代码,则需要使用Meteor.subscribe()显式预订集合。 subscribe()接受一个回调,该回调将在客户端上初始文档集时运行。

看到:

meteor-publish
meteor-subscribe

关于meteor - meteor -在客户端启动时使用集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10099968/

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