[Solved] Create and use a global function?


#1

Hello!

I’m starting with meteor and I would like to create a global function in a function.js file.
Then I would like to use this function in another template helpers.

I tried to create a ‘registerHelper’:

UI.registerHelper('myFunction', function(some, parameters){
	// return something
});

How can I use this function in another document ?
On an other forum, I found this:

Template.videos.helpers({
	var1: function(){
		return UI._registerHelper('myFunction')('my', 'parameter');
	},
	var2: function(){
		return UI._registerHelper('myFunction')('an', 'otherparameter');
	}
});

But it didn’t work and the console returns this error:

Exception in template helper: TypeError: UI._registerHelper is not a function

Could you help me to solve this problem?

Thank you!


#2

Put it in a package and export it.


#3

What you are doing here is not creating a generic global function, you are creating a global Template helper. Note also that UI.registerHelper is deprecated syntax for Template.registerHelper - check the documentation for what this does.

If you just want a generic, global function, just create a generic, global function:

myFunction = function(a,b) {
  // do something
}

However, you will need to ensure the file containing this is loaded ahead of its use. Of course, you really shouldn’t be polluting the global namespace with random names, so you would preferably define this within the context of a template (normally in the onCreated callback), or if it must be global, within a suitable namespace.


#4

Oh, thank you so much robdallow!

I know UI.registerHelper is deprecated but meteor change faster than tutorials and forums.

I didn’t know this synthax. I tried with:

function myFunction(a,b) {
    // Do something
}

And of course, didn’t work.
I just try your synthax, it’s just perfect!

Thanks!


#5

Global helpers can also be called via Blaze._globalHelpers.nameOfHelper() if I recall correctly.