Reputation: 5254
I'm scratching my head at this because I remember this exact code working at some point in the past. When test
is created and rendered I set the value of this.data
but I can't retrieve it in events or helpers. I'm beginning to think that a package or something screwed up my Meteor.
<template name="test">
<button>click me</button>
</template>
Template.test.onCreated(function(){
// here I am setting the data context of the test template
this.data = {
doors: 5
};
// when I hover over `this` in Chrome is indeed shows the object
debugger
});
Template.test.onRendered(function(){
this.data = {
wheels: 4
};
// when I hover over `this` it also shows the object
debugger
var changeDataContext = function(obj){
this.data = obj;
};
changeDataContext( {engine: 1} );
// when I hover over `this` it shows the old value of `this`, not the new one with {engine: 1}
this;
debugger
});
Template.test.events({
'click button': function(e, tmpl){
tmpl;
// when I hover over `tmpl` it shows null for `data`???
debugger
}
});
Template.test.helpers({
images: function () {
this;
// when I hover over `this` it shows null for the value of `this`???
debugger
return this.wheels;
}
});
EDIT
Here is a MeteorPad outlining the problem:
http://meteorpad.com/pad/Cqw3fWieJfspK2eYv/Leaderboard
Check out the debugger statements here:
http://app-5p5urzku.meteorpad.com/
Upvotes: 0
Views: 102
Reputation: 4820
This is an issue with your scopes. First, for onRendered
, you cannot use this
inside a function and expect it to be considered like this
from a higher scope:
Template.test.onRendered(function(){
this.data = {
wheels: 4
};
var self = this; // we save this scope's `this` for later
var changeDataContext = function(obj){
this.data = obj; // here, `this` refers to the current scope, ergo your changeDataContext function! onRendered's `this` does not get altered.
self.data = obj; // here, we refer to the `self` variable that you set earlier. It should work.
};
changeDataContext( {engine: 1} );
// tadaaaaaaaaaa
this;
debugger
});
Then, for helpers: this
represents the data context, not the template instance. If you want the template instance, use Template.instance()
:
Template.test.helpers({
images: function () {
var tmpl = Template.instance();
if (tmpl.data)
return tmpl.data.wheels;
}
});
Please note: the data context is different from Template.instance().data
. You cannot put stuff into this.data
in onCreated
and expect to be able to use it in your Spacebars template. Iron router just stores it there as well for convenience.
As for your event... Well there, it should work. What you wrote should show you wheels
. Maybe you are altering your instance's data
in a way beforehand? To be sure, you can use Template.instance()
instead of tmpl
Upvotes: 2