English 中文(简体)
Meteor - Using collection on client startup
原标题:
  • 时间:2012-04-11 04:50:42
  •  标签:
  • meteor

Why this code shows "0"? Shouldn t it return "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"});
    });
}

If I do the "Messages.find().count()" later, it returns 1.

最佳回答

By default, when a Meteor client starts up, it connects to the server and subscribes to documents in any Meteor.Collection you defined. That takes some time to complete, since there s always some amount of delay in establishing the server connection and receiving documents.

Meteor.startup() on the client is a lot like $() in jQuery -- it runs its argument once the client DOM is ready. It does not wait for your client s collections to receive all their documents from the server. So the way you wrote the code, the call to find() will always run too early and return 0.

If you want to wait to run code until after a collection is first downloaded from the server, you need to use Meteor.subscribe() to explicitly subscribe to a collection. subscribe() takes a callback that will run when the initial set of documents are on the client.

See:

meteor-publish and meteor-subscribe

问题回答

Just to follow up with a code example of how to know when a collection is ready to use on the client.

As @debergalis described, you should use the Meteor.subscribe approach - it accepts a couple of callbacks, notably onReady

For example:

if(Meteor.isClient){

    Meteor.subscribe("myCollection", {

        onReady: function(){

            // do stuff with my collection

        }

    });

}




相关问题
Problems to run examples in Meteor

I m testing Meteor examples and this is what I see when I run meteor in todos examples: Unexpected mongo exit code 100. Restarting. Unexpected mongo exit code 100. Restarting. Unexpected mongo exit ...

Handlebars Exception

Any hints what the following exception might be about? Running on: http://localhost:3000/ No dependency info in bundle. Filesystem monitoring disabled. Errors prevented startup: Exception while ...

How easy to call external Web APIs in Meteor?

Does (or will) Meteor provide a library to handle external Web API calls? E.g. to build a Meteor app that integrates with Facebook Graph API or Google Spreadsheet API.

Meteor - Using collection on client startup

Why this code shows "0"? Shouldn t it return "1"? Messages = new Meteor.Collection("messages"); if (Meteor.is_client) { Meteor.startup(function () { alert(Messages.find().count()); ...

热门标签