parkej3
parkej3

Reputation: 111

Issue accessing "this.data" from within Template

From what I can tell from the documentation, you can access a Templates data context from within the rendered callback by using "this.data". However whenever I try this, i just get undefined. Example using the basic meteor example here https://gist.github.com/4362039

Anyone else having an issue with this? Or have a working example where you access this.data?

Upvotes: 1

Views: 732

Answers (2)

zorlak
zorlak

Reputation: 1404

@parkej3, you're correct that this.data is the way to access a template's data context from the created, rendered, and destroyed callbacks. HOWEVER: it's important to be careful with this (pun intended) because the this in the created, rendered, and destroyed callbacks is the template instance, whereas in template helpers, this refers to the template's data context.

this.data will be undefined when the template in question isn't called using a data context.

As @Rahul mentioned, a template will have a data context if it's rendered inside of a {{#with}} or {{#each}} block, in which cases those statements give the template instance its data context. {{#with contextObject}} assigns contextObject to this.data, while {{#each items}}{{>item}}{{/each}} will set the item template's this.data to the item in question for each of the items.

Upvotes: 7

Rahul
Rahul

Reputation: 12231

In the same documentation, if you scroll up a bit, you'll find the following sentence:

Template instance objects are found as the value of this in the created, rendered, and destroyed template callbacks and as an argument to event handlers.

So as Diogenes suggested, you're looking for this. this.data is useful for if you have nested templates and want to find the context object you're currently inside of (such as in cases where you have a Template containing an {{#each}} loop).

Upvotes: 2

Related Questions