Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
  }
});
like image 461
Ramesh Murugesan Avatar asked Mar 31 '15 09:03

Ramesh Murugesan


Video Answer


2 Answers

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(){...};
like image 55
saimeunt Avatar answered Oct 04 '22 04:10

saimeunt


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.

like image 22
Daniel Avatar answered Oct 04 '22 04:10

Daniel