如何在meteor模板中创建全局函数

如何在meteor模板中创建全局函数,meteor,meteor-blaze,meteor-helper,Meteor,Meteor Blaze,Meteor Helper,如何为meteor中的所有模板创建函数 index.js // Some function function somefunction(){ return true; } // Some function somefunction = function(){ return true; }; Test1.js Template.Test1.events({ 'click button' : function (event, template){ //call somefun

如何为meteor中的所有模板创建函数

index.js

// Some function
function somefunction(){
  return true;
}
// Some function
somefunction = function(){
  return true;
};
Test1.js

Template.Test1.events({
  'click button' : function (event, template){
    //call somefunction
  }
});
Test2.js

Template.Test2.events({
  'click button' : function (event, template){
    //call some function
  }
});

您需要将函数设置为全局标识符,以便能够跨多个文件调用它:

index.js

// Some function
function somefunction(){
  return true;
}
// Some function
somefunction = function(){
  return true;
};
在Meteor中,默认情况下变量是文件范围的,如果要将标识符导出到全局命名空间以在整个项目中重用它们,则需要使用以下语法:

myVar = "myValue";
在JS中,函数是可以存储在正则变量中的文本,因此采用以下语法:

myFunc = function(){...};

如果不想浪费全局名称空间,可以创建单独的文件:

导入/functions/somefunction.js

在模板的逻辑中,将其导入并以这种方式使用:

client/calculations.js


可能您并不希望这样,因为在这种情况下,您应该在任何模板中追加import,但避免使用全局变量是一种很好的做法,并且您可能不希望在任何模板中使用相同的函数

它不需要在代码的任何特定部分中。如果它在另一个文件中,则对于全局函数,即global.js,只需从template.js文件导入它,并像往常一样调用它。

可能重复的