Ramesh Murugesan
Ramesh Murugesan

Reputation: 5013

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

Upvotes: 11

Views: 8724

Answers (3)

Eneas Marín
Eneas Marín

Reputation: 164

It doesn't need to be in any specific part of your code. If it's in another file, for global functions i.e. global.js just import it from your template .js file and call it as usual.

Upvotes: 0

Daniel
Daniel

Reputation: 8647

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.

Upvotes: 1

saimeunt
saimeunt

Reputation: 22696

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

Upvotes: 22

Related Questions