How to access variable created in 'onRendered' from Helpers or Event

Hello all,

I need to get variable value created in ‘onRendered’. How to access the variable from Helpers or Event.

Please advice, thanks.

In the on* handlers, you have access to the current template instance with this (attention, do not use arrow functions). You can easily get the template instance in your event handlers and helpers with Template.instance().

Also I’d like to note that unless it is instance dependent, using a simple variable scoped accordingly could be better.

Template.my_template.onRendered(function(){
    this.variable = true;
});
Template.my_template.helpers({
    'my_helper':function(){
        return Template.instance().variable;
    }
});
1 Like

Hi,

Template.my_template.onRendered(function(){
    let secondVar = 'Hello World';
    this.variable = true;
});
Template.my_template.helpers({
    'my_helper':function(){
        return Template.instance().variable;
    }
});

I can only access ‘variable’ value as your example but I’m unable to access ‘secondVar’. I tried Template.instance().secondVar as well as Template.instance().data.secondVar

What is the proper way to access 'secondVar'? Please advice, thank you.

let secondVar = 'Hello World'; should be this.secondVar = 'Hello World';

1 Like

Ok noted, thanks… Will use 'this' for variable assignment in such case.

1 Like