how to create a global function in meteor template

Ramesh Murugesan picture Ramesh Murugesan · Mar 31, 2015 · Viewed 8.5k times · Source

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

Answer

saimeunt picture saimeunt · Mar 31, 2015

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(){...};