【问题标题】:Meteor - How call another function in same template helperMeteor - 如何在同一个模板助手中调用另一个函数
【发布时间】:2016-04-29 16:29:50
【问题描述】:

我正在尝试 Meteor。我只想从一个函数调用另一个函数,它给了我参考错误说 xxx 未定义。

在我的 html 文件中:

<template name="hello">
    {{getDaysInMonth}} 
</template>

在js文件中:

Template.hello.helpers({
  getDaysInMonth: function(){
    var now = new Date();
    return getDaysInParticularMonth(now.getMonth(), now.getFullYear()); // Meteor does not find this function
  },
  getDaysInParticularMonth: function(month, year) {
     console.log("hey"); 
     return 0;     //just for test
  },

});

输出

 ReferenceError: getDaysInParticularMonth is not defined

请帮忙。谢谢,

【问题讨论】:

    标签: javascript meteor


    【解决方案1】:

    有一个技巧,您可以使用流星从右到左执行函数调用,因此您的一个函数输出将是另一个函数的输入,依此类推。我希望这对你有意义。

    你的html代码

    <template name="hello">
        {{getDaysInParticularMonth getDaysInMonth}} 
    </template>
    

    你的 js 代码

    Template.hello.helpers({
      getDaysInMonth: function(){
        var now = new Date();
        return [now.getMonth(), now.getFullYear()];
      },
      getDaysInParticularMonth: function(array) {
         console.log("hey"); 
         return 0;     //just for test
      },
    });
    

    但是如果你只想从助手调用一个函数,那么你必须在助手块之外定义函数,这也是你可以做到的。

    在我的 html 文件中:

    <template name="hello">
        {{getDaysInMonth}} 
    </template>
    

    在js文件中:

    Template.hello.helpers({
      getDaysInMonth: function(){
        var now = new Date();
        return getDaysInParticularMonth(now.getMonth(), now.getFullYear());
      },
    
    });
    
    function getDaysInParticularMonth(month, year) {
         console.log("hey"); 
         return 0;     //just for test
    },
    

    【讨论】:

      【解决方案2】:

      在模板助手之外声明一个方法

      function commonMethod(month, year) {
          console.log("hey"); 
          return 0;     //just for test
      }
      
      Template.hello.helpers({
        getDaysInMonth: function(){
          var now = new Date();
          return commonMethod(now.getMonth(), now.getFullYear()); // Meteor does not find this function
        },
        getDaysInParticularMonth: function(month, year) {
          var now = new Date();
          return commonMethod(now.getMonth(), now.getFullYear());
        },
      });
      

      【讨论】:

      • 原始代码失败的任何原因?为什么 Template.instance().methodname() 也不起作用?
      猜你喜欢
      • 2019-04-07
      • 1970-01-01
      • 2014-12-12
      • 2013-06-18
      • 2015-03-28
      • 1970-01-01
      • 2015-10-19
      • 2014-11-28
      • 2013-06-15
      相关资源
      最近更新 更多