how to create a global function in meteor template
Asked Answered
P

3

11

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
  }
});
Paletot answered 31/3, 2015 at 9:0 Comment(1)
Possible duplicate of Global function for Meteor template helperThereon
C
22

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(){...};
Coextend answered 31/3, 2015 at 9:5 Comment(0)
W
1

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.

Wicketkeeper answered 17/6, 2017 at 8:57 Comment(0)
E
0

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.

Epiphysis answered 20/9, 2018 at 15:48 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.