meteormeteor-blazemeteor-helper

how to create a global function in meteor template


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

Solution

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