What is the difference between Template.Instance () and template.data?

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

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

against

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

Both of them seem to bring up the same data. Is there a reason why I should do this?

+5
source share
2 answers

A similar question here:

The difference between Template.instance () and this

To understand that:

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

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

So, pay attention to the important thing here: The data context may change over time if your data changes upstream:

If you transfer data to the template, the template will be resubmitted 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 can be in this (i.e. 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 become the new data context and will NOT contain your added data.

So in short:

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

you should:

 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 the helper and events through

Template.instance().myKey

+7
source

Actually, Template.instance() (with a lower i), and since this function returns the current template instance in the area (the one from which the event occurred), there is no difference with the second parameter of the event handler, which also runs the current template instance, therefore, you can easily access template data using Template.instance().data or t.data in the event handler.

However, there is an easier way to access the current data context inside the event handler: the this object is bound to the data context in which the event was triggered.

+2
source

Source: https://habr.com/ru/post/1215156/


All Articles