Meteor:为什么我会通过将函数(){}切换为()=>来丢失我的数据上下文;{}

Meteor: Why am I losing my data context by switching function() { } to () => { }?

本文关键字:gt 上下文 数据 我的 函数 为什么 Meteor      更新时间:2023-09-26

因此,我正在试验ES6,安装了grigio:babel包,并开始遍历我的es5代码,并在遇到问题时将其更新为一些新的ES6语法。

最初我的模板助手看起来是这样的:

Template.exampleTemplateName.helpers({
   exampleHelper: function() {
      //returns an array from Mongo Collection
   }
});

在Blaze每个环路中使用的

{{#each exampleHelper}}
{{/each}}

正如您所料,我为该事件循环中的元素提供的所有事件处理程序都可以访问Mongo Collection中的字段,该字段由exampleHelper通过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
    }
});

因此,我通过Babeljs的在线翻译器运行了上面的ES6代码,并收到了以下内容,这显然是不正确的,因为我不想要命名函数:

Template.exampleTemplateName.helpers({
     exampleHelper: function exampleHelper() {}
});

有人能告诉我正确的语法应该是什么样子吗?

有人能告诉我正确的语法应该是什么样子吗?

您的原始代码完全正确。你不必滥用这些功能,只为了使用它们、保存一些密钥等而使用它们。在这种情况下,你应该使用普通的匿名函数。

this指向全局对象的原因是,箭头函数就是这样工作的:它们有词法this,而不是动态。这意味着this引用在函数创建时静态绑定到函数上下文(在您的情况下是window(,而不是在运行时动态解析。

此代码将不起作用(它将显示窗口对象(:

Template.homePage.helpers({
  exampleHelper: function () {
    return [
      {text: 'this'}, {text: 'that'}, {text: 'the other thing'}
    ];
  },
  process: () => {
    console.log(this);
  }
});

因为当你使用=>语法时,它想做这样的事情:

var self = this;
process(function () {
  doSomethingWith(self);
});

因此,在这种情况下,this确实等于window。解决方案是在这种情况下不使用=>