2015-03-31 59 views
11

如何为流星中的所有模板创建一个函数?如何在流星模板中创建全局函数

index.js

// Some function 
function somefunction(){ 
    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 
    } 
}); 
+0

可能的[流星模板助手的全局函数]的副本(http://stackoverflow.com/questions/20681761/global-function-for-meteor-template-helper) – 2016-01-11 13:02:53

回答

20

你需要让你的函数的全局标识符能够跨越叫它多个文件:

index.js

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

流星,变量文件范围在默认情况下,如果你想标识导出到全局命名空间跨项目重复使用它们,你需要使用这个语法:

myVar = "myValue"; 

在JS,功能是可以存储在常规变量文字,因此语法如下:

myFunc = function(){...}; 
0

如果你不希望弄乱全局命名空间,您可以创建单独的网络连接乐:

进口/功能/ somefunction.js

export function somefunction(a,b) { 
    return a+b; 
} 

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

客户端/ calculations.js

import { somefunction } from '../imports/functions/somefunction.js' 

Template.calculations.events({ 
    'click button' : function (event, template){ 
     somefunction(); 
    } 
}); 

也许它不完全是你想要的,因为在这种情况下,你应该在任何模板中追加导入,但是避免使用全局变量是相当好的做法,并且可能你不想在任何模板中使用相同的函数。

相关问题