I have the following global helper:
Template.registerHelper('results',function(){
var valuationId = this._id;
var valuation = Valuations.findOne({_id: valuationId});
var targetId = this.targetId;
var targetTicker = Companies.findOne({_id:targetId}).ticker;
var targetData = CompaniesData.findOne({ticker: targetTicker});
return {
peFy1: targetData.epsFy1 * valuation.PriceEarningsFy1,
peFy2: targetData.epsFy2 * valuation.priceEarningsFy2
}
});
When I call this helper through HTML, like so, it works fine:
<div>
{{results.peFy1}}
</div>
I am not able to display the value when calling the helper through Javascript, per this answer.
<div>
{{peFy1}}
</div>
Template.ValuationResults.helpers({
peFy1: function() {
return UI._globalHelpers.results().peFy1;
}
});
I've tried writing this in a couple other ways but none work:
return UI._globalHelpers['results']().peFy1;
return Template._globalHelpers.results().peFy1;
For what it's worth, UI._globalHelpers
gives an error in Webstorm as being unresolved variables.
I thought the problem might be that I am not passing any parameters to the function, but it works fine through HTML so shouldn't be necessary. Also, adding console.log(this._id)
and console.log(this.targetId)
within the test
helper both return correct results, so those are valid.
CORRECT CODE USING ANSWER BELOW:
getResults = function(valuationId,targetId){
var valuation = Valuations.findOne({_id: valuationId});
var targetTicker = Companies.findOne({_id:targetId}).ticker;
var targetData = CompaniesData.findOne({ticker: targetTicker});
return {
peFy1: targetData.epsFy1 * valuation.priceEarningsFy1,
peFy2: targetData.epsFy2 * valuation.priceEarningsFy2
}
};
Template.registerHelper('results',function(){
return getResults();
});
Template.Valuation.helpers({
peFy1: function() {
var valuationId = this._id;
var targetId = this.targetId;
return getResults(valuationId,targetId).peFy1;
},
peFy1: function() {
var valuationId = this._id;
var targetId = this.targetId;
return getResults(valuationId,targetId).peFy1;
}
});