Reputation: 2910
I have a blaze template like this:
{{>jobsheetsTable companyId=companyId}}
In the JS for the template I have the onCreated function like this ...
Template.jobsheetsTable.onCreated(function(){
const instance = this;
instance.companyId = new ReactiveVar();
console.log(instance, instance.data, instance.data.companyId);
if(instance.data.companyId){
instance.companyId.set(instance.data.companyId);
}
}
The issue is that in the console.log statement I notice something odd ...
instance
is correctly outputting the instance with the data
object and a companyId
instance.data
however returns {companyId: undefined}
.
I am not changing instance.data
anywhere and the function being passed into this template does not change the companyId
.
Update: Using meteor 1.6.1.
Upvotes: 0
Views: 168
Reputation: 16478
The onCreated
callback is only run once per template creation, so the data you get is the one that is provided to the initial creation (likely with you attribute set to undefined
).
It is likely that the data context is changed after the initial rendering, and this does not trigger the function. as the template is not re-created.
If you are certain that you want to track the data context in the onCreated
callback, you need to set a reactive dependency on it, using the Template.currentData()
reactive data source. Since it needs to be inside a reactive context in order to be re-run when the data changes, you will need to create one, and a convenient method of doing so is via this.autorun()
, which stops the computation for you when the template is destroyed.
Template.jobsheetsTable.onCreated(function(){
this.companyId = new ReactiveVar();
this.autorun(() => { // creates a reactive computation
const data = Template.currentData(); // creates a reactive dependency
console.log('data context', data);
if(data.companyId){
this.companyId.set(data.companyId);
}
})
});
The code above contains an autorun
block that will re-run whenever the data context changes.
Upvotes: 2