全局帮助程序在HTML中调用时有效,而不是在JS中调用

时间:2015-10-11 21:52:14

标签: javascript meteor 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
            }
});

当我通过HTML调用此帮助程序时,它就可以正常工作:

<div>
    {{results.peFy1}}
</div>

通过Javascript per this answer调用帮助程序时,我无法显示该值。

<div>
    {{peFy1}}
</div>

Template.ValuationResults.helpers({
    peFy1: function() {
        return UI._globalHelpers.results().peFy1;
    }
});

我尝试用其他几种方式写这个但没有用:

return UI._globalHelpers['results']().peFy1;
return Template._globalHelpers.results().peFy1;

对于它的价值,UI._globalHelpers在Webstorm中将错误视为未解析的变量。

我认为问题可能是我没有将任何参数传递给函数,但它可以通过HTML正常工作,所以不应该是必要的。此外,在console.log(this._id)帮助程序中添加console.log(this.targetId)test都会返回正确的结果,因此这些结果都是有效的。

使用以下答案的正确代码:

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

1 个答案:

答案 0 :(得分:0)

您对UI._globalHelpers.results().peFy1的使用在语法上看起来是正确的。

然而,作为回避Meteor(UI._globalHelpers)api的替代选项,请创建一个标准的JavaScript函数,如下所示:

getResults = function(){
  var valuationId = this._id;
  var valuation = Valuations.findOne({_id: valuationId});
  var targetId = this.targetId;
  var targetTicker =     Companies.findOne({_id:targetId}).ticker;
  console.log('targetId: ' + targetId);
  console.log(Companies.findOne({_id:targetId})),
  var targetData = CompaniesData.findOne({ticker: targetTicker});
  return {
        peFy1: targetData.epsFy1 * valuation.PriceEarningsFy1,
        peFy2: targetData.epsFy2 * valuation.priceEarningsFy2
        }
};
Template.registerHelper('results',function(){
  return getResults();
});

在模板中使用results帮助程序,在JavaScript中使用getResults函数。