How does Template.currentData() work behind the scenes?

This is more a behind the scenes question and maybe the only real answer is for me to dig through the Template/Blaze code, but here’s the question anyway:

How is it that these two pieces of code return different data?

Template.comments.onCreated(function () {
  var currentData = Template.currentData();
Template.posts.onCreated(function () {
  var currentData = Template.currentData();

No arguments are sent in and this isn’t used either, so how does Template.currentData() know in which context it was called?

Without having looked at the source at all, probably because in one cases you’re passing your function to the onCreated method of Template.posts and in the other to Template.comments which probably have their own, separate data contexts maintained by Meteor.

EDIT: With a quick look at the source, Template.currentData() is just a wrapper for Blaze.getData(). If you call Blaze.getData() with no arguments it grabs the data context from the view 'with', which probably relates to how Meteor handles data contexts and views.

Maybe someone more knowledgeable can chime in.

It uses a global dynamic variable which is set to the right value before onCreated is called, and reset after the call finishes. This has one negative side effect: if you do an async operation inside onCreated, you need to save the value returned from Template.currentData() yourself.

1 Like

Thanks. So Template is constantly changing to refer to something else. That confused me for a while, but makes sense now.