Meteor template data context not available in temp

2019-09-07 11:24发布

问题:

I use the template data context inside a template's created function.

Template.temp.created = function() { console.log('this.data'); };

When I go to the page normally--i.e. click the link to the page--I see the console log the correct data object. When I hit the refresh button on the page, this.data is null.

Why?


Also, I am using iron-router to set the data context:

...
this.route('temp', {
    ...
    data: function() { return MyCollection.findOne(someId); },
    ...
}
...

回答1:

If you want to wait until data come then use waitOn.

this.route('temp', {
    waitOn:function(){
      return this.subscribe("nameOfPublishFunction");
    },
    data: function() { return MyCollection.findOne(someId); },
    ...
}

Remember to activate loading hook (thanks @Peppe L-G):

Router.onBeforeAction("loading");

IronRouter docs #waitOn

Update

Here you can find sample meteor app with iron:router package which shows how turning loading hook on and off ( Router.onBeforeAction("loading")) changes availability of data to created and rendered methods.