How to create a function for all the templates in meteor?
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
}
});
You need to make your function a global identifier to be able to call it across multiple files :
index.js
// Some function
somefunction = function(){
return true;
};
In Meteor, variables are file-scoped by default, if you want to export identifiers to the global namespace to reuse them across your project, you need to use this syntax :
myVar = "myValue";
In JS, functions are literals that can be stored in regular variables, hence the following syntax :
myFunc = function(){...};
If you do not want to litter global name-space you can create separate file:
imports/functions/somefunction.js
export function somefunction(a,b) {
return a+b;
}
and in logic of template import it and use in this way:
client/calculations.js
import { somefunction } from '../imports/functions/somefunction.js'
Template.calculations.events({
'click button' : function (event, template){
somefunction();
}
});
Maybe it is not exactly this, that you want, because in this case you should append import in any template, but avoiding of global variables is rather good practice, and probably you do not want to use the same function in any template.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With