Search code examples
javascriptnode.jsmeteorhandlebars.js

Session.get does not set variable in Meteor.js


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)
        }
    });

}());

Solution

  • 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.