Use Meteor Iron Router data context in regular JS file?
Iron Router Code:
this.route('petProfile', {
path: '/pets/:_id',
data: function(){
return Adoptees.findOne(this.params._id);
}
});
It's pretty straightforward. If I have a key petName
for every object in the collection Adoptees
, I can simply use handlebars templates to access the data context.
petProfile.html:
<template name="petProfile">
<h1>{{petName}}</h1>
</template>
But say that I want to have a data context in a linked javascript file:
petProfile.js:
Template.petProfile.rendered = function() {
var petName = //How do I get the pet name from the data context in Iron Router?
}
Great, it works. So based on saimeunt's answer, I can simply do:
petProfile.js:
Template.petProfile.rendered = function() {
var petName = this.data.petName;
}
source to share
In the callback, created / rendered / destroyed
you can access the data context using this.data.field
, because it is this
matched against a template instance.
In helpers and event handlers, you can access it using this.field
because it is this
displayed directly in the data context.
source to share