Nyxynyx
Nyxynyx

Reputation: 63619

Meteor.startup on the client

When using the following code on the client side, why is the variable init in if(init) evaluated to be true even though it comes before init = true and no new documents are added to the Orders collection? This results in the query.observe returning all documents returned by the query, not just newly added ones.

This behavior is not observed on the server side, which only executes the console.log when new documents are added.

Meteor.startup(function() {

    var init = false
    var query = Orders.find()
    var handle = query.observe({
        added: function (doc) {
            if(init)
                console.log(doc)
        }
    });

    init = true

})

Upvotes: 2

Views: 2016

Answers (1)

Tarang
Tarang

Reputation: 75945

This is because everything is synchronous on the server whereas everything is asynchronous on the client.

init=true will be set after the query.observe operation is finished, but on the client it could be set before this as init would be set to true almost as immediately as the observe handle is run.

You would have to use a different kind of behavior to make it work in the way you expect on the client.

Maybe use something that gets the timestamp after a subscription is complete, and then only continue if the current timestamp is higher:

Meteor.subscribe("yourdocs", function() {
    Session.set("yourdocs_finishtime", new Date().getTime());
});

Then your added handle:

added: function (doc) {
    var subtime = Session.get("yourdocs_finishtime");
    if(subtime && (subtime < new Date().getTime()))
        console.log(doc);
}

Upvotes: 3

Related Questions