2

In an effort to avoid repeating code I found it useful to have helper functions that could be called from within a foo.rendered function (for instance). Why is this possible in 0.9.3 of Meteor, but throws an error in 1.0 ?

Template.foo.helpers({
  'fooFn' : function(){
     return "something"  
  }
});

Template.foo.rendered = function(){
  var something = Template.foo.fooFn();
}

Should I change the syntax in foo.rendered (am I calling it wrong?) or maybe use a different approach entirely (set up functions outside of the helpers({}) and rendered() and call those? or set this up as a registered helper function?

typeofgraphic
  • 312
  • 4
  • 11
  • 1
    How about defining the function fooFn outside and use it in both `Template.foo.helpers({'fooFn' : fooFn});` and `var something = fooFn();` – user3557327 Nov 04 '14 at 20:36
  • Seems like a good option, thanks. I am eager to hear from any other Meteor developers and how they structure apps when functions internal to a template are required.. – typeofgraphic Nov 06 '14 at 12:14

2 Answers2

5

It looks like it is possible as of Meteor 1.0.3.1 to find and call helper functions, although it is clear it's not supposed to be used like this.

Still it can be done:

Template.foo.__helpers[" fooFn"]()

Please notice the leading space for the function name.

The other way of dealing with this is attaching a function to a global namespace, then calling that from somewhere else in your code, as user3557327 mentioned.

Additionally you can use:

Template.registerHelper('myHelper', function (){return 'Look At Me!'})

to register a global helper, and call it explicitly using:

UI._globalHelpers['myHelper']()
MrMowgli
  • 873
  • 7
  • 23
  • 1
    If you want to apply a data context for the first option, you will need to call it with apply() like so: `Template.foo.__helpers[" fooFn"].apply(contextObject, parameterArray)` – MrMowgli Feb 20 '15 at 04:04
1

I think this would be a better method: How to use Meteor methods inside of a template helper

Define a function and attach it to the template. Call that function from rendered, as well as your template helper. Like MrMowgli said, you probably aren't "supposed" to call template helpers from within the .js file, only from the ...that could probably break in the future.

For example define a function and attach it to the tamplate:

Template.Play.randomScenario = function () { // HACK HACK HACK }

and then call it from your lifecycle method

Template.Play.created = function () {

  Template.Play.randomScenario();

};

scenario: function () {
    return Template.Play.randomScenario();;
  },

I had the same problem and this is the solution I used. Hope that helps.

Community
  • 1
  • 1
Vincil Bishop
  • 1,594
  • 17
  • 21