Reputation: 63599
fruit
is a variable that is shared between template helpers Template.fruits.name
and Template.fruits.nick
to prevent duplicating code in each individual helper function.
However when the change #fruit-selector
event handler is triggered, the shared variable fruit
does not change even though its set by Session.get('fruit')
.
Does this mean I cannot use this approach of declaring fruit
variable as shown if I want it to be reactive?
main.js
(function() {
// Set default fruit
if(!Session.get('fruit')) {
Session.set('fruit', 'apple');
}
var fruit = Session.get('fruit');
Template.fruits.name = function() {
return fruit;
};
Template.fruits.nickname = function() {
return fruit + 'y';
};
Template.fruits.name2 = function() {
return Session.get('fruit');
};
Template.fruits.events({
'change #fruit-selector': function(e) {
Session.set('fruit', e.target.value);
console.log('fruit: ' + fruit)
}
});
}());
Upvotes: 0
Views: 3813
Reputation: 1
Looks like, session is no longer part of the default meteor package. Go to command prompt and run "meteor add session"
Upvotes: 0
Reputation: 336
Try this (did you mean Template.fruit.nickname or Template.fruits.nickname?):
(function() {
// Set default fruit
if(!Session.get('fruit')) {
Session.set('fruit', 'apple');
}
Template.fruits.name = function() {
return Session.get('fruit');
};
Template.fruit.nickname = function() {
return Session.get('fruit') + 'y';
};
Template.fruits.name2 = function() {
return Session.get('fruit');
};
Template.fruits.events({
'change #fruit-selector': function(e) {
Session.set('fruit', e.target.value);
console.log('fruit: ' + Session.get('fruit'))
}
});
}());
Upvotes: 0
Reputation: 8345
You must use Session.get('fruit')
inside the template helpers, otherwise they won't respond to the changes (fruit
is not a reactive data source, it has got it value from a reactive data source).
PS
Use Session.setDefault('fruit', 'apple')
, instead of your approach.
Upvotes: 1