使用es6时,流星模板自动运行不是一个功能

Sim*_*mon 4 meteor ecmascript-6

作品

Template.Hello.onRendered(function() {
  this.autorun(() => {
    console.log('sup');
  });
});
Run Code Online (Sandbox Code Playgroud)

不行.

Template.Hello.onRendered(() => {
  this.autorun(() => {
    console.log('sup');
  });
});
Run Code Online (Sandbox Code Playgroud)

错误是TypeError:_this.autorun不是函数.

使用箭头符号的任何想法都会给我们这个错误?

Exp*_*lls 7

箭头函数使用词法绑定,this这意味着this它将是创建函数时的任何内容.这意味着,在使用对象属性(如模板)的对象上创建函数时,遗憾的是您无法使用它.

一个小例子是这样的:

o = {};
o.fn = () => console.log(this);
o.fn(); // not 'o'

o.fn = function () { console.log(this); }
o.fn(); // 'o'
Run Code Online (Sandbox Code Playgroud)

.autorun是模板的一种方法,因此this需要功能绑定.

有时候箭头函数的词法绑定很有用,例如在回调中autorun.在这种情况下,您希望this保持与外部范围相同.否则你必须绑定它:

Template.Hello.onRendered(() => {
  this.autorun(() => {
    console.log(this); // the template
  });
  this.autorun(function () {
    console.log(this); // the template
  }.bind(this));
  this.autorun(function () {
    console.log(this); // the callback function
  });
});
Run Code Online (Sandbox Code Playgroud)