我想在页面加载后尽快执行Meteor集合查询.我尝试的第一件事是这样的:
I want to perform a Meteor collection query as soon as possible after page-load. The first thing I tried was something like this:
Games = new Meteor.Collection("games"); if (Meteor.isClient) { Meteor.startup(function() { console.log(Games.findOne({})); }); }但是,这不起作用(它显示"undefined").从JavaScript控制台调用该查询后,几秒钟后,该查询就会生效.我认为在数据库准备就绪之前会有些滞后.那么如何知道该查询何时成功?
This doesn't work, though (it prints "undefined"). The same query works a few seconds later when invoked from the JavaScript console. I assume there's some kind of lag before the database is ready. So how can I tell when this query will succeed?
在OSX 10.8和Chrome 25下的流星版本0.5.7(7b1bf062b9).
Meteor version 0.5.7 (7b1bf062b9) under OSX 10.8 and Chrome 25.
推荐答案您应首先publish来自服务器的数据.
You should first publish the data from the server.
if(Meteor.isServer) { Meteor.publish('default_db_data', function(){ return Games.find({}); }); }在客户端上,仅在从服务器加载数据之后才执行收集查询.这可以通过在subscribe调用内使用反应式会话来完成.
On the client, perform the collection queries only after the data have been loaded from the server. This can be done by using a reactive session inside the subscribe calls.
if (Meteor.isClient) { Meteor.startup(function() { Session.set('data_loaded', false); }); Meteor.subscribe('default_db_data', function(){ //Set the reactive session as true to indicate that the data have been loaded Session.set('data_loaded', true); }); }现在,当您执行集合查询时,您可以通过以下方式检查数据是否已加载:
Now when you perform collection queries, you can check if the data is loaded or not as:
if(Session.get('data_loaded')){ Games.find({}); }注意::删除autopublish程序包,它默认将所有数据发布到客户端,这是不明智的做法.
Note: Remove autopublish package, it publishes all your data by default to the client and is poor practice.
要删除它,请在根项目目录中的每个项目上执行$ meteor remove autopublish.
To remove it, execute $ meteor remove autopublish on every project from the root project directory.
更多推荐
流星:我怎么知道数据库什么时候准备好了?
发布评论