Calling a template helper method from a different method/event?


#1

I’ve been wrestling with this issue for awhile now.

I was able to make it work by registering the method I was trying to call as a global helper, but I figured there had to be a better way.

Example:

((home.js))

if (Meteor.isClient) {
  Template.home.events({
    'click button': function() {
      sayHello();  // Error
    }
  });

  Template.home.helpers({
    sayHello() {
      console.log("hello");
    }
  });
}

If the helper is in the same file, is there no way to call the sayHello method without registering it as a global helper? I’ve been trying to figure out how to write reusable code, and it seems like things like this are making it really tough. But I’m sure that I’m just missing something here.

Thank you!


#2

A helper is used to connect Blaze templates to logic, it’s not a normal function. The return values of a helper function are returned to the Blaze template, so you could call your helper function via {{sayHello}} there. Calling a helper function from an event handler wouldn’t make much sense.

To achieve what you probably want (= a local function that you can call from an event handler), you would write:

function sayHello() {
  console.log("hello");
}

Template.home.events({
  'click button': function() {
    sayHello();
  }
});

#3

If you want to write a lot of reusable code / components, I can recommend you www.viewmodel.org for Blaze - it makes things much easier. In your case above, you need to write the sayHello method once and could use it as template helper and within your events.


#4

Omg. Thank you so much. I don’t know why I was under the impression that all of my methods had to be nested inside of the Meteor functions (onCreated, helpers, events, etc…)


#5

You’re welcome. I know it’s hard to understand at the beginning. I had the same troubles :slight_smile:


#6

You might also want to take a look at space:template-controller. It pairs very well with the 1.3 Guide and you can define private helper methods accessible in your .js file only. You can read the simple API here.