Arrow functions use lexical binding of this
which means that this
will be whatever it was when the function was created. This means that you unfortunately can't use it when creating functions on objects that use object properties such as the template.
A small example is something like:
o = {};
o.fn = () => console.log(this);
o.fn(); // not 'o'
o.fn = function () { console.log(this); }
o.fn(); // 'o'
.autorun
is a method of the template so the functional binding of this
is required.
There are times when the lexical binding of arrow functions are useful such as in the callback to autorun
. In that case, you want this
to remain the same as the outer scope. Otherwise you would have to bind it:
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
});
});