Calling one helper from another helper in the context of a template (Meteor 0.9.4)

Starting with Meteor 0.9.4, the definition of Template.MyTemplate.MyHelperFunction () is no longer valid.

We have deprecated the syntax for Template.someTemplate.myHelper = ... in favor of Template.someTemplate.helpers (...). Using the old syntax still works, but it displays a warning on the console.

This seemed good to me, as it would at least save the incorrect and duplicated text. However, I soon discovered that the way to create Meteor apps was prone to making this new version out of date. In my applications, I defined helpers / functions with the old syntax, and then called these methods from other helpers. I found this 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 seem to be available with the new method proposed by Meteor (which makes me think that I was wrong all the time). My question is: What is the preferred way to share common template logic between template helpers?

+5
source share
1 answer

Sorry if I'm bored, but could you declare the function as an object and assign it to several 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 that you constantly duplicate the same helpers across several templates, this may help to use Template.registerHelper instead of assigning the same function to several places.
+3
source

Source: https://habr.com/ru/post/1204873/


All Articles