0

I have a function in helpers. I want to call that function in my next function. How can I fall it ?

'first_func' ()
{
    return "hello";
},
'second_func' ()
{
    return this.first_func();
}

This is not working. I want to call first function in second one.

Thank YoU!

Maria Kari
  • 25
  • 1
  • 6
  • Are these methods of an object? And how do you call the function? – Ram Jun 26 '16 at 16:58
  • No they are not object. Just defined in Template.test.hepers({}); – Maria Kari Jun 26 '16 at 17:02
  • You are passing `{}` to the function which is an object and those functions are methods of the object. `this` is dynamic and value of it depends on how a function is called. Check https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/this – Ram Jun 26 '16 at 17:04
  • I don't know a good use case for this but if you really want to use it then please see this question: http://stackoverflow.com/q/17229302/4699406 – Jan Jouke Tjalsma Jun 26 '16 at 17:06
  • Okay. What other method do you suggest ? – Maria Kari Jun 26 '16 at 17:06
  • [This forum post](http://stackoverflow.com/questions/32042886/how-do-you-call-a-meteor-template-helper-from-the-console-or-other-js-code) might be helpful to you. – Jeremy Iglehart Jun 27 '16 at 03:17

2 Answers2

1

With the way you're trying to do this, you would not need this. So you would be able to call the first function like so:

function first_func() {
   //`this` is bound to first_func()
   return "hello";
}

function second_func () {
   //`this` is bound to second_func()
   return first_func();
}

second_func(); // returns 'hello'

It appears, however, that you're trying to call functions within a class or a method. I can't guess at how or why, though, so please see the answer at Can you write nested functions in JavaScript?

Community
  • 1
  • 1
thatgibbyguy
  • 4,033
  • 3
  • 23
  • 39
0

Like @thatgibbyguy says, you can just define a function in the same file and use it. In a Meteor template helper, this is the data context of the helper, not the template instance itself.

Template.myTemplate.helpers(
  first_func(){
    return myFunction();
  },
  second_func(){
    return myFunction();
  }
);
function myFunction(){
   return "Hello"
}

You can also register a global helper which can be used from any template

Michel Floyd
  • 18,793
  • 4
  • 24
  • 39