Template.onRendered can't access 'this._id'

I’m working on a website, and I’m trying to run some code once the template is rendered. I have tested it with console.log and it runs it once the template is rendered, but I’m using iron:router and I don’t know how to access this._id.

The routing code is as follows:

Router.route('/play/:_id', {
template: 'example',
data: function(){
    var currentItem = this.params._id;
    return mydb.findOne({ _id: currentItem });


I’m trying to use ‘this’ to get information from the database about the page that I’m on. For example, my collection has a field named ‘name’. I’m trying to access it using ‘this.name

And here’s the code for the onRendered function:

Template.example.onRendered(function() {

It logs before, but returns null on this.name.
Any help is appreciated greatly :slight_smile:

try this.data._id and this.data.name and just this.data

With that, I get the error

TypeError: this.data is null

in the console.

However when I just use console.log(this) (I forgot to add this in my last post) I get

 Object { view: Object, data: null, firstNode: <div.infotab.fademein>, lastNode: <div.tools.fademein>, _allSubsReadyDep: Object, _allSubsReady: false, _subscriptionHandles: Object }

written out into the console.

Make sure you are “populating” that template correctly

Sorry, I’m new, what do you mean exactly?

try this

you should see if those variable are properly set.

in your Template.example.onRendered I’m pretty sure you should use this.data.SOMETHING

Tested it - the variables are properly set, though I’m not sure I should this.data, as I have some template events that occur when a key is pressed, and they can access the database through this.SOMETHING just fine…

in a event

"keypress: function(){
console.log(this.SOMETHING); // in here this.SOMETHING is fine

console.log(this.data.SOMETHING); // here is different

if the variable is properly set in your router there is something wrong how you call that template… but I don’t see it from here

I see - thanks for all the help :slight_smile:

In event callbacks you actually get the event and template in the parameters of the callback

 'keypress input': function(event, template) {
  // code

as for onRendred, you need to make sure that your subscription is ready when it gets called or data will be empty

Do you have a suggested method of delaying when the template gets called?