How can I access ReactiveVar
in the construction like below?
Template.profile.helpers({
user: {
...
gender: () => Template.instance().genderFlag.get(), //returns Uncaught TypeError: Cannot read property 'genderFlag' of null
...
},
});
Returns error
because Template.instance()
inside gender:
is null
(when I console.log(Template.instance());
)
This is how I create ReactiveVar:
Template.profile.onCreated( function() {
this.genderFlag = new ReactiveVar(0);
});
P.S. gender
is inside user
because I use user
context i.e. {{#with user}}
in my .html.
UPDATE:
Spacebars part:
<button type="button" name="Male" class="{{#if gender '1'}}gender--selected{{/if}}">Male</button>
<button type="button" name="Female" class="{{#if gender '2'}}gender--selected{{/if}}">Female</button>
so I am passing arg
to the Template.helper
gender
:
user: {
...
gender: (arg) => arg == Template.instance().genderFlag.get(),
...
}
Because you are creating a function within the helper it seems to be picking up the wrong data context and therefore the Template variable is not available a the time it is called, the following code works, it moves the function to the helper itself so the context is correct and it can access Template.instance()
correctly, then you can return an object for user as needed for your #with
Template.profile.helpers({
user: () => {
return {
...
gender: Template.instance().genderFlag.get()
...
};
}
});
EDIT:
In line with the update to your question, couple of options but neatest I would say is:
Template.profile.helpers({
user: () => {
var gend = Template.instance().genderFlag.get();
return {
...
gender: gend,
isMale: gend===1?"gender--selected":"",
isFemale: gend===2?"gender--selected":"",
...
};
}
});
And in your handlebars
<button type="button" name="Male" class="{{isMale}}">Male</button>
<button type="button" name="Female" class="{{isFemale}}">Female</button>