简体   繁体   English

从template中调用帮助程序函数。在Meteor.js中呈现,错误为1.0,精细为0.9.3

[英]Calling helper functions from within template.rendered in Meteor.js, error in 1.0, fine in 0.9.3

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). 为了避免重复代码,我发现拥有可以从foo.rendered函数(例如)中调用的辅助函数很有用。 Why is this possible in 0.9.3 of Meteor, but throws an error in 1.0 ? 为什么在Meteor的0.9.3中可能出现这种情况,但在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? 我应该更改foo.rendered中的语法(我称错吗?)还是应该完全使用其他方法(在helpers({})和render()外部设置函数并调用它们?还是将其设置为a注册助手功能?

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. 从Meteor 1.0.3.1开始,似乎可以找到并调用辅助函数,尽管很明显, 应该这样使用它。

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. 解决此问题的另一种方法是将函数附加到全局名称空间,然后从代码中的其他位置调用该功能,如user3557327所述。

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']()

I think this would be a better method: How to use Meteor methods inside of a template helper 我认为这将是一个更好的方法: 如何在模板帮助器中使用Meteor方法

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. 就像MrMowgli所说的那样,您可能不是“应该”从.js文件中调用模板帮助程序,而只是从...中调用,将来可能会中断。

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. 希望能有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM