As of Meteor 0.9.4, defining Template.MyTemplate.MyHelperFunction() is no longer valid.
We deprecated the Template.someTemplate.myHelper = ... syntax in favor of Template.someTemplate.helpers(...). Using the older syntax still works, but it prints a deprecation warning to the console.
This seemed fine to me, as it would (at the least) save some mis-typing and duplicated text. However, I soon discovered that the way I was building Meteor apps had leaned on an ability that this new version has deprecated. In my apps, I've been defining helpers/functions with the old syntax, then calling those methods from other helpers. I found it helped me keep my code clean and consistent.
For example, I might have a control like this:
//Common Method
Template.myTemplate.doCommonThing = function()
{
/* Commonly used method is defined here */
}
//Other Methods
Template.myTemplate.otherThing1 = function()
{
/* Do proprietary thing here */
Template.myTemplate.doCommonThing();
}
Template.myTemplate.otherThing2 = function()
{
/* Do proprietary thing here */
Template.myTemplate.doCommonThing();
}
But this does not appear to be available with the new method Meteor suggests (which makes me think I was wrong all along). My question is, What is the preferred way to share common, template-specific logic between a template's helpers?
Sorry if I'm being dull, but couldn't you declare the function as an object and assign it to multiple helpers? For instance:
// Common methods
doCommonThing = function(instance) // don't use *var* so that it becomes a global
{
/* Commonly used method is defined here */
}
Template.myTemplate.helpers({
otherThing1: function() {
var _instance = this; // assign original instance *this* to local variable for later use
/* Do proprietary thing here */
doCommonThing(_instance); // call the common function, while passing in the current template instance
},
otherThing2: function() {
var _instance = this;
/* Do some other proprietary thing here */
doCommonThing(_instance);
}
});
By the way, if you notice you're constantly duplicating the same helpers across multiple templates, it might help to use Template.registerHelper
instead of assigning the same function to multiple places.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With