我正在尝试使用ES6,安装了grigio:babel包,并开始逐步更新我的es5代码以使用一些新的ES6语法,但是我遇到了一个问题。
最初我的模板助手看起来像这样:
Template.exampleTemplateName.helpers({
exampleHelper: function() {
//returns an array from Mongo Collection
}
});
这段代码用于在Blaze each循环中使用:
{{#each exampleHelper}}
{{/each}}
如你所料,在这个事件循环中,所有元素的事件处理程序通过exampleHelper
返回的Mongo Collection字段可以通过this
关键字访问。 this.exampleField
会返回我期望的内容。
现在我开始升级到ES6,但某些原因导致以下语法破坏了数据上下文,因此this
不再返回预期的结果,而是返回Window
:
Template.exampleTemplateName.helpers({
exampleHelper() {
//returns an array from Mongo Collection
}
});
上述是我的第一次尝试,然后我尝试了:
Template.exampleTemplateName.helpers({
exampleHelper: () => {
//returns an array from Mongo Collection
}
});
所以我将上述ES6代码通过Babeljs的在线翻译器运行,得到了以下结果,显然是不正确的,因为我不想要一个命名函数:
Template.exampleTemplateName.helpers({
exampleHelper: function exampleHelper() {}
});
有人能告诉我正确的语法应该是什么样子的吗?
this
,它们像任何其他来自父上下文的变量一样闭合this
。 - zwolexampleHelper
中引用this
?由于你有{{#each exampleHelper}}
,所以this
不会指向该数组中的项。 - CaptSaltyJackexampleHelper
中没有引用this
,而是在所有绑定到{{#each}}生成的元素的事件处理程序中引用this
。这非常方便。 - Kris