Reputation: 1766
I have a test collection ("initData") which already contains some documents and the following code on a Meteor client:
Meteor.subscribe("initData");
Meteor.startup(function () {
console.log(InitData.findOne("randIdTest").key);
Deps.autorun(function() {
var allInitData = InitData.find();
allInitData.forEach(function(entry) {
console.log("Deps foreach: " + entry._id);
});
var randomObject = InitData.findOne("randIdTest");
console.log("Deps call " + randomObject.key);
});
});
var InitDataObserver = InitData.find().observe({
added: initDataChange,
changed: initDataChange,
removed: initDataChange
});
function initDataChange () {
var allInitData = InitData.find();
allInitData.forEach(function(entry) {
console.log("Observer foreach: " + entry._id);
});
var randomObject = InitData.findOne("randIdTest");
console.log("Observer call " + randomObject.key);
}
My initial goal was to find the best way to use data from a collection as soon as it is loaded in the client, as this is not the case when Meteor.startup is triggered. (In the Code above on line 4 I get an error as InitData.findOne("randIdTest") is undefined at that moment.)
I tried to accomplish this with Deps.autorun() and observe() as you can see above. observe() works as you would expect. However Deps.autorun() doesn't get triggered at all (no matter if I delete, modify or add documents - and I've also tried to put it outside the Meteor.startup(fucntion(){})).
Am I understanding Deps.autorun() wrong or have I implemented it wrong? In which case should I use Deps.autorun() and when observe()?
Upvotes: 0
Views: 394
Reputation: 8013
Firstly, from the docs:
If the initial run of an autorun throws an exception, the computation is automatically stopped and won't be rerun.
So if your Meteor.startup
block is executing before your subscription to InitData
is ready and randomObject
is undefined, as appears to be the case given that an error is thrown, your Deps.autorun
won't run again regardless of what you do.
There are methods in the iron-router package to deal with this situation very easily, and I would recommend you explore them. In the above example it's obviously quite straightforward to avoid the error being thrown on the first run by just checking whether randomObject
is defined, which should get the Deps.autorun
to work as expected. Either this or the observe
block would seem to do the trick for the use case you describe as both will be triggered when the minimongo DB is populated on the client, but an iron-router solution may be cleaner.
Upvotes: 1