Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the Difference between Template.Instance() vs template.data?

Tags:

meteor

When creating a Meteor event handler, what's the difference between...

'click .something': function(e,t){
    var data = t.data
}

vs

'click .something': function(e,t){
    var data = Template.instance().data
}

They both seem to bring up the same data. Is there a reason why I should one or the other?

like image 831
Mcope Avatar asked Mar 11 '15 16:03

Mcope


1 Answers

Similar question here:

Difference between Template.instance() and this

The thing to realize is that:

In the template life-cycle functions (onCreated, onRendered...) this is equal to Template.instance() so this.data is the same as Template.instance().data AT THAT TIME!

In a helper or event, this is the current data context.

So, note an important thing here: the Data context can change over time if your data changes upstream:

If you pass data to a template, the template will be re-rendered with the new data. New data = new data context.

So if you do something like:

Template.example.onCreated(function() {
   this.data.myKey = "my example data set on template creation"; //WRONG!
   // or equivalently:
   Template.instance().data.myOtherKey = "another key"; //WRONG!
})

well, this data may be under this (i.e. the data context) in your helper (this.myKey) but only as long as the upstream data does not change.

As soon as the upstream data changes, this will be the new data context, and will NOT contain your added data.

So, in summary:

If you need to add context to your template in onCreated or onRendered, make sure you do NOT bind it to the current data context, but to the Template.instance()

you should do:

Template.example.onCreated(function() {
   this.myKey = "my example data set on template creation"; 
   // or equivalently:
   Template.instance().myOtherKey = "another key"; 
})

and you can access this data in helper and events via

Template.instance().myKey

like image 64
MrE Avatar answered Sep 30 '22 02:09

MrE