Search code examples
meteormeteor-blaze

Difference between Blaze.getData() and Template.currentData() and use cases for each of them


I tried with Blaze.getData() and Template.currentData() under Template.onRendered which gives me same result.Can any one help me in explaining the differences between with use cases. I looked over Meteor Docs which explains

Template.currentData() :

  • Inside an onCreated, onRendered, or onDestroyed callback, returns the data context of the template.
  • Establishes a reactive dependency on the result.

Blaze.getData([elementOrView]) :

  • Returns the current data context, or the data context that was used when rendering a particular DOM element or View from a Meteor template.

Also what does Establishes a reactive dependency on the result this mean under Template.currentData


Solution

  • Template.currentData() gets you the current data for a given template, within the onCreated, onRendered or onDestroyed.

    remember you are creating template instances, so there may be different data for the same template, but different instances of it.

    In a given instance, under Helpers, you get the data under the this context. In the onCreated, onRendered, this is one level up, and this.data is the data.

    currentData means it is the data at the time of create/render etc... but the data can change: if your template takes data from a #each loop for example, which itself comes from a collection, chances are the data will first be undefined, then populated with values, and change as the subscription receives data.

    currentData makes this reactive, which means the result will be updated when new data comes.

    Blaze.getData([elementOrView]) is to get the data context from an element or view, that is, not necessarily within a Template. It can be a DOM element or Blaze.View

    That means that this function lets you figure what was the data context when the element was rendered, after the facts. maybe to check if an element contains an expected value, from another Template helper or event for example.